import { h, Host, Env } from "@stencil/core";
import { search, sendFeedback, checkStatus, getConfig, insertStyles } from "../../utils/utils";
// import InputForm from "./components/Form"
import SearchResult from "./components/SearchResult";
import { SocketService } from "../../utils/socket-service";
import { setCtaElement } from "../../utils/global-store";
import { executeRecaptcha } from "../../utils/botHelpers/reCaptchaHelpers";
import { generateUUID, loadLanguageFile, insertCustomCSS, insertCustomJS, detectLanguage, isMac, setLocalData, isOutsideClick, createAutoResetTimer, clearTimer, validateFormInput, createChatMessage, updateChatHistory, removeLastMessage, isMaxQuestionsReached, getConversationHistory, } from "../../utils/ctaHelpers";
import { ai12zManager } from "../../utils/ai12z-manager";
import { filterConversationHistoryByProjectAndConfig } from "../../utils/ctaHelpers";
import { setParentComponentState } from "../../utils/state/app-store";
export class Ai12zCta {
    constructor() {
        this.test = "123";
        this.cdnPath = "https://cdn.ai12z.net/assets/cta";
        this.dirty = false;
        this.isSubmitted = false;
        this.pButtonText = "Ask AI";
        this.pPlaceholder = "AI search...";
        this.pHelpText = "Enter text to get started";
        this.pNoResultsText = "No results found";
        this.errorMsg = "Error please try again!";
        this.pheading = "";
        this.isCta = false;
        this.dataKey = Env.DATA_KEY || "";
        this.dataMode = Env.DATA_MODE || "prod";
        this.options = {};
        this.excludeTags = [];
        this.includeTags = [];
        this.ctaSettings = {};
        this.showModal = false;
        this.questionCounter = 0;
        this.formData = { search: "", displayText: "" };
        this.searchResults = [];
        this.error = null;
        this.conversationId = null;
        this.canRender = true;
        this.chatHistory = [];
        this.isChat = false;
        this.aiMessageId = null;
        this.announceMessage = "";
        this.showHistory = false;
        this.conversationHistory = [];
        this.isRendered = false; // Flag to track if the component has been rendered
        this.sendSurveyData = async (surveyData) => {
            // const query = "Here is the data you requested:" + surveyData.results
            // surveyData.domId = surveyData.domId.replace("surveyContainer-", "")
            // this.thumbsId = this.generateUUID()
            // this.aiMessageId = `ai-message-${this.generateUUID()}`
            const jsonData = "This JSON is from a form submission" + surveyData.results;
            this.sendJSON(jsonData, surveyData.completeText);
            // const res = null
            // const res = await askAI(this.dataKey, this.dataMode, query, surveyData.conversationId, true, this.dataAttributes)
            // const idx = this.chatHistory.findIndex(item => item.id === surveyData.domId)
            // const lastMessage = {
            //   message: res?.answer,
            //   type: "ai",
            //   status: "success",
            //   insightId: res?.insight_id,
            //   formModel: res?.formModel,
            //   thumbsId: this.thumbsId,
            //   id: this.aiMessageId,
            // }
            // if (idx === -1) {
            //   // this.handleSubmit(null, query, "survey-res", false, null)
            //   this.chatHistory.splice(this.chatHistory.length - 1, 1)
            //   this.chatHistory = [...this.chatHistory, lastMessage]
            // } else {
            //   this.chatHistory = [...this.chatHistory.slice(0, idx), lastMessage, ...this.chatHistory.slice(idx + 1)]
            // }
            // this.startStream.emit({ search: query })
        };
        this.detectTextByLang = () => {
            const shortLang = detectLanguage();
            loadLanguageFile(shortLang)
                .then(data => {
                // console.log("data", data)
                // this.langData = data
                this.pButtonText = data.button_text;
                this.pPlaceholder = data.placeholder_text;
                this.pHelpText = data.help_text;
                this.pNoResultsText = data.results_text;
                this.errorMsg = data.error_message;
            })
                .catch(error => {
                console.error("Error loading language file:", error);
            });
        };
        this.handleSubmit = async (event, value, type, followUp, imgFiles, options = { isHide: false }) => {
            var _a, _b, _c, _d, _e, _f;
            if (type === "history") {
                this.showHistory = true;
                this.isChat = false;
                const conversationList = getConversationHistory("ai12z-cta-history");
                this.conversationHistory = filterConversationHistoryByProjectAndConfig(conversationList, (_a = this.ctaSettings._id) === null || _a === void 0 ? void 0 : _a.$oid, this.ctaSettings.pId);
                return;
            }
            if (type === "ask-ai") {
                this.questionCounter++;
                setLocalData(`ai12z-cta-data`, { qCounter: this.questionCounter });
            }
            this.dirty = true;
            this.isSubmitted = true;
            event === null || event === void 0 ? void 0 : event.preventDefault();
            this.formData = Object.assign(Object.assign({}, this.formData), { search: value });
            if (this.chatHistory.length === 0 && ((_b = this.ctaSettings) === null || _b === void 0 ? void 0 : _b.autoResetTimer) > 0 && type === "ask-ai") {
                this.startTimer();
            }
            if (!followUp && type === "follow-up") {
                this.chatHistory = [];
                this.isChat = false;
                this.showHistory = false;
                this.displayMessage();
            }
            if (type === "survey") {
                this.chatHistory = removeLastMessage(this.chatHistory);
            }
            if (validateFormInput(this.formData.search, imgFiles)) {
                this.isSubmitted = false;
                this.stateChanged.emit(false);
                return;
            }
            try {
                let response = { answer: "", formModel: null, insight_id: null };
                if (type === "ask-ai" || this.isChat) {
                    if (!this.socketService) {
                        this.socketService = SocketService.createInstance(this.dataMode, this.dataKey);
                        // Wait for socket to connect before proceeding
                        await this.socketService.waitForConnection();
                    }
                    this.isChat = true;
                    this.chatHistory.push(createChatMessage(this.formData.displayText !== "" ? this.formData.displayText : this.formData.search, "user", "success", imgFiles));
                    this.chatHistory[this.chatHistory.length - 1].isHide = (_c = options.isHide) !== null && _c !== void 0 ? _c : false;
                    // this.aiMessageId = `ai-message-${generateUUID()}`
                    this.aiMessageId = "";
                    this.thumbsId = generateUUID();
                    this.chatHistory.push(createChatMessage(`<div class="animate-ping">...</div>`, "ai", "pending", undefined, this.aiMessageId));
                    if (imgFiles && imgFiles.length > 0) {
                        this.imgFiles = imgFiles;
                        //response = await askImgAI(this.dataKey, this.dataMode, imgFiles, this.formData.search)
                    }
                    else {
                        this.imgFiles = [...[]];
                        //  response = await askAI(this.dataKey, this.dataMode, this.formData.search, this.conversationId, followUp,this.dataAttributes)
                    }
                    //this.conversationId = response.conversation_id
                    this.chatHistory = removeLastMessage(this.chatHistory);
                    response.answer = ((_d = this.ctaSettings) === null || _d === void 0 ? void 0 : _d.maxQuestion) > 0 && this.questionCounter > ((_e = this.ctaSettings) === null || _e === void 0 ? void 0 : _e.maxQuestion) ? this.ctaSettings.msgLimit : response === null || response === void 0 ? void 0 : response.answer;
                    //response.answer = response.answer.replace(RegExp(/\[[^>]*]/gm),'<div id="surveyContainer"></div>');
                    const lastMessage = createChatMessage(response === null || response === void 0 ? void 0 : response.answer, "ai", "success", undefined, this.aiMessageId, response === null || response === void 0 ? void 0 : response.insight_id, this.thumbsId, response === null || response === void 0 ? void 0 : response.formModel);
                    this.chatHistory = updateChatHistory(this.chatHistory, lastMessage);
                    // console.log("chatHistory")
                    // Wait for Chat component to render and attach listeners
                    requestAnimationFrame(() => {
                        var _a;
                        if (isMaxQuestionsReached(this.questionCounter, (_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a.maxQuestion)) {
                            // console.log("Max question limit reached on cta")
                            const eventData = { search: this.formData.search, maxQuestion: true, chatData: this.chatHistory[this.chatHistory.length - 1] };
                            this.startStream.emit(eventData);
                        }
                        else {
                            // console.log("type", typeof this.formData.search)
                            const eventData = { search: this.formData.search, imgFiles: this.imgFiles };
                            this.startStream.emit(eventData);
                        }
                    });
                }
                else {
                    if ((_f = this.ctaSettings) === null || _f === void 0 ? void 0 : _f.autoSearch) {
                        response = await search(this.dataKey, this.dataMode, this.formData.search);
                        this.displaySearchResults(response);
                    }
                }
            }
            catch (error) {
                console.error(error);
                this.error = error;
            }
            finally {
                this.isSubmitted = false;
                this.stateChanged.emit(false);
                // this.formData.search = ""
                this.formData.displayText = "";
            }
        };
        this.displaySearchResults = results => {
            this.searchResults = results.docs;
            this.isSubmitted = false;
            this.showHistory = false;
        };
    }
    // @Watch("placeholder")
    // watchPlaceHolder(newValue: string, oldValue: string) {
    //   if (newValue === oldValue) {
    //     return
    //   }
    //   this.pPlaceholder = newValue
    // }
    async openModal() {
        var _a;
        this.showModal = true;
        this.dirty = false;
        ai12zManager.setActive("cta");
        // this.invokeSocket()
        if ((_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a.clearMemory) {
            this.clearSearchHistory();
        }
        requestAnimationFrame(() => {
            var _a;
            const searchInput = this.el.shadowRoot.querySelector("ai12z-input-form").querySelector("textarea");
            searchInput.focus();
            this.el.shadowRoot.querySelector(".modal-wrapper").classList.add("show-modal");
            if (document.querySelector("ai12z-bot")) {
                const botEle = document.querySelector("ai12z-bot");
                (_a = botEle.shadowRoot.querySelector(".layout")) === null || _a === void 0 ? void 0 : _a.classList.add("hide-chatbot");
            }
        });
        this.open.emit();
        this.setLocalData();
        this.isElementAvailable.emit(true);
        // this.socketService = SocketService.createInstance(this.dataMode)
    }
    setLocalData() {
        const ctaData = { qCounter: this.questionCounter };
        setLocalData(`ai12z-cta-data`, ctaData);
    }
    async sendMessage(message, displayText) {
        this.formData.search = message;
        this.formData.displayText = displayText !== null && displayText !== void 0 ? displayText : message;
        this.handleSubmit(null, this.formData.search, "ask-ai", false, null);
        this.messageSent.emit(message);
    }
    async sendJSON(jsonData, displayText) {
        this.formData.search = JSON.stringify(jsonData);
        this.formData.displayText = displayText;
        this.handleSubmit(null, this.formData.search, "ask-ai", false, null);
        this.messageSent.emit(jsonData);
    }
    async closeModal() {
        var _a;
        this.el.shadowRoot.querySelector(".modal-wrapper").classList.remove("show-modal");
        if (document.querySelector("ai12z-bot")) {
            const botEle = document.querySelector("ai12z-bot");
            (_a = botEle.shadowRoot.querySelector(".layout")) === null || _a === void 0 ? void 0 : _a.classList.remove("hide-chatbot");
            // botEle.shadowRoot.querySelector("bot-popover")?.classList.remove("hide-chatbot")
        }
        setTimeout(() => {
            var _a;
            this.showModal = false;
            this.stopStream.emit({ socketId: (_a = this.socketService) === null || _a === void 0 ? void 0 : _a.getSocketId() });
            this.socketService = null;
            this.close.emit();
            clearTimer(this.timer);
        }, 300); // Assuming 300ms is your transition duration
    }
    handleKeyDown(ev) {
        var _a;
        if (!this.showModal)
            return;
        if ((ev.metaKey || ev.ctrlKey) && ev.key === "k") {
            ev.preventDefault();
            this.openModal();
        }
        if (ev.key === "Escape") {
            ev.preventDefault();
            if ((_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a.allowClose) {
                this.closeModal();
            }
            else {
                // Announce to screen readers that closing is not allowed
                this.announce("This dialog cannot be closed with Escape. Please complete your interaction.");
            }
        }
    }
    surveyHandler(_state) {
        //this.handleSubmit(null, _state.detail.results, _state.detail.type, false, null)
        if (_state.detail.type === "button") {
            this.formData.displayText = "";
            this.handleSubmit(null, _state.detail.results, _state.detail.type, false, null);
            this.buttonClicked.emit(_state.detail.results);
        }
        else if (_state.detail.type === "carousel") {
            this.chatHistory = [...this.chatHistory, _state.detail.results];
        }
        else if (_state.detail.type === "update") {
            const idx = this.chatHistory.findIndex(item => item.id === _state.detail.results.id);
            this.chatHistory = updateChatHistory(this.chatHistory, _state.detail.results, idx);
        }
        else if (_state.detail.type === "sendMessage") {
            // console.log("sendMessage", _state.detail.results)
            if (_state.detail.results.length > 1) {
                this.sendMessage(_state.detail.results[0], _state.detail.results[1]);
            }
            else {
                this.sendMessage(_state.detail.results[0]);
            }
        }
        else if (_state.detail.type === "sendJSON") {
            this.sendJSON(_state.detail.results[0], _state.detail.results[1]);
        }
        else {
            const surveyData = _state.detail;
            const jsonData = `This JSON is from a form submission [${surveyData.keyName}]: ${JSON.stringify(surveyData.results, null, 2)}. There is no need to show the form [${surveyData.keyName}] again.`;
            this.formData.search = jsonData;
            this.formData.displayText = surveyData.completeText;
            this.handleSubmit(null, this.formData.search, "ask-ai", false, null, { isHide: true });
            // this.sendSurveyData(_state.detail)
        }
    }
    formSubmittedHandler(event) {
        event.stopPropagation();
        // console.log("Form submitted", event.detail)
        this.formSubmitted.emit(event.detail.data);
    }
    async componentWillLoad() {
        insertStyles(`https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css`, this.el);
        setParentComponentState("cta", this.dataKey, this.dataMode);
        await this.configCtaSettings();
        // console.log("componentWillLoad ai12z-cta.tsx")
        // this.socket = this.socketService.getSocket()
        // this.socketService = SocketService.createInstance(this.dataMode)
        const slot = this.el["children"];
        let slotHasContent = slot && slot.length > 0;
        this.detectTextByLang();
        if (slotHasContent) {
            for (var i = 0; i < slot.length; i++) {
                // console.log(slot[i].tagName.toLowerCase())
                if (slot[i].tagName.toLowerCase() === "cta" || slot[i].getAttribute("slot") === "cta") {
                    this.isCta = true;
                }
            }
        }
    }
    onDataKeyChange(_v) {
        setParentComponentState("cta", this.dataKey, this.dataMode);
    }
    onDataModeChange(_v) {
        setParentComponentState("cta", this.dataKey, this.dataMode);
    }
    clearSearchHistory() {
        if (this.searchResults && this.searchResults.length > 0) {
            this.searchResults.splice(0, this.searchResults.length);
            this.searchResults = [...this.searchResults];
        }
        this.chatHistory = [];
        this.isChat = false;
        this.clearInput.emit(false);
        this.clearResults.emit(false);
    }
    handleOutsideClick(ev) {
        var _a;
        if (isOutsideClick(ev, "modal-wrapper")) {
            if ((_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a.allowClose) {
                this.closeModal();
            }
            else {
                // Announce to screen readers that closing is not allowed
                this.announce("This dialog cannot be closed by clicking outside. Please complete your interaction.");
            }
        }
    }
    announce(message) {
        this.announceMessage = message;
        setTimeout(() => {
            this.announceMessage = "";
        }, 1000);
    }
    startTimer() {
        var _a;
        this.timer = createAutoResetTimer(() => {
            this.questionCounter = 0;
            // const endTime = Date.now()
            // console.log(`Timer executed after ${endTime} milliseconds`)
            setLocalData(`ai12z-cta-data`, { qCounter: this.questionCounter });
        }, (_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a.autoResetTimer);
    }
    connectedCallback() {
        //this.parseMyObjectProp(this.myObject);
        checkStatus(this.dataKey, this.dataMode).then(enable => {
            this.canRender = enable;
            // if (!enable) {
            //   console.log("ai12z canRender", this.canRender)
            // }
        });
        // this.configCtaSettings()
    }
    async configCtaSettings() {
        const payload = {
            apiKey: this.dataKey,
            configId: this.configId,
            configType: "search",
        };
        getConfig(payload, this.dataMode)
            .then(data => {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
            // console.log("data", data)
            if (data) {
                // console.log("Web Settings", data)
                this.ctaSettings = data;
                if ((_a = data === null || data === void 0 ? void 0 : data.v3) === null || _a === void 0 ? void 0 : _a.siteKey) {
                    executeRecaptcha(data._id, data.v3.siteKey, "search", this.dataKey, this.dataMode, detail => {
                        this.errored.emit(detail);
                    })
                        .then(response => {
                        if (response) {
                            this.isRendered = true;
                        }
                    })
                        .catch(err => {
                        console.error("Recaptcha verification failed:", err);
                        this.isRendered = false;
                    });
                }
                else {
                    this.isRendered = true;
                }
                if (((_b = this.ctaSettings) === null || _b === void 0 ? void 0 : _b.autoSearch) === undefined) {
                    this.ctaSettings.autoSearch = true;
                }
                if (((_c = this.ctaSettings) === null || _c === void 0 ? void 0 : _c.allowClose) === undefined) {
                    this.ctaSettings.allowClose = true;
                }
                if (((_d = this.options) === null || _d === void 0 ? void 0 : _d.allowClose) !== undefined) {
                    this.ctaSettings.allowClose = this.options.allowClose;
                }
                if (((_e = this.ctaSettings) === null || _e === void 0 ? void 0 : _e.clearMemory) === undefined) {
                    this.ctaSettings.clearMemory = true;
                }
                if (((_f = this.ctaSettings) === null || _f === void 0 ? void 0 : _f.enableMobileView) === undefined) {
                    this.ctaSettings.enableMobileView = true;
                }
                if (((_g = this.ctaSettings) === null || _g === void 0 ? void 0 : _g.categorize) === undefined) {
                    this.ctaSettings.categorize = true;
                }
                if (this.ctaSettings.customCSS) {
                    this.insertCustomCSS(this.ctaSettings.customCSS);
                }
                if (this.ctaSettings.customJS) {
                    insertCustomJS(this.el.shadowRoot, this.ctaSettings.customJS);
                }
                if ((_h = this.ctaSettings.welcome) === null || _h === void 0 ? void 0 : _h.styles) {
                    this.insertCustomCSS(this.ctaSettings.welcome.styles);
                }
                if ((_j = this.ctaSettings.welcome) === null || _j === void 0 ? void 0 : _j.scripts) {
                    insertCustomJS(this.el.shadowRoot, this.ctaSettings.welcome.scripts);
                }
                if ((_k = this.ctaSettings.helpText) !== null && _k !== void 0 ? _k : (_l = this.ctaSettings.welcome) === null || _l === void 0 ? void 0 : _l.message) {
                    this.pHelpText = (_m = this.ctaSettings.helpText) !== null && _m !== void 0 ? _m : (_o = this.ctaSettings.welcome) === null || _o === void 0 ? void 0 : _o.message;
                }
                if (this.ctaSettings.theme) {
                    let themeLink = "";
                    if (this.ctaSettings.theme !== "custom") {
                        themeLink = `${this.cdnPath}/v2/themes/theme-${this.ctaSettings.theme}.css`;
                    }
                    else {
                        themeLink = this.ctaSettings.customTheme;
                    }
                    const linkEl = document.createElement("link");
                    linkEl.setAttribute("rel", "stylesheet");
                    linkEl.setAttribute("href", themeLink);
                    document.head.appendChild(linkEl);
                }
                else {
                    const linkEl = document.createElement("link");
                    linkEl.setAttribute("rel", "stylesheet");
                    linkEl.setAttribute("href", `${this.cdnPath}/v2/themes/theme-default.css`);
                    document.head.appendChild(linkEl);
                }
                if (this.ctaSettings.inputFieldPosition === "bottom") {
                    this.ctaSettings.textareaAtBottom = true;
                }
                else {
                    this.ctaSettings.textareaAtBottom = false;
                }
            }
        })
            .catch(error => {
            console.error("Error loading configuration:", error);
        });
    }
    insertCustomCSS(css) {
        // console.log("css", css)
        insertCustomCSS(this.el.shadowRoot, css);
    }
    componentDidLoad() {
        setCtaElement(this.el);
        // console.log("Component has been rendered")
        // ✅ Auto-register with manager
        ai12zManager.register("cta", this);
    }
    deleteChatHistoryHandler(event) {
        var _a, _b, _c;
        const chatHistory = getConversationHistory("ai12z-cta-history");
        const filteredHistory = filterConversationHistoryByProjectAndConfig(chatHistory, (_b = (_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a._id) === null || _b === void 0 ? void 0 : _b.$oid, this.ctaSettings.pId);
        const updatedHistory = chatHistory.filter(item => {
            if (!filteredHistory.includes(item)) {
                return true;
            }
            return item.conversationId !== event.detail.conversationId;
        });
        localStorage.setItem("ai12z-cta-history", JSON.stringify(updatedHistory));
        this.conversationHistory = filterConversationHistoryByProjectAndConfig(updatedHistory, (_c = this.ctaSettings._id) === null || _c === void 0 ? void 0 : _c.$oid, this.ctaSettings.pId);
    }
    chatClickHandler(event) {
        if (event.detail.length > 0) {
            this.chatHistory = event.detail;
            this.isChat = true;
            requestAnimationFrame(() => {
                var _a;
                const chatEl = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector("ai12z-chat");
                chatEl === null || chatEl === void 0 ? void 0 : chatEl.hydrateMessagesFromState();
            });
        }
        // this.messages = event.detail
        // this.showWelcomeScreen = false
        // this.hideInput = false
        this.showHistory = false;
    }
    defaultTemplate() {
        const isMacOS = isMac();
        return (h("button", { type: "button", class: "flex ring-1  ring-slate-900/10 hover:ring-slate-300 focus:outline-none focus:ring-2 focus:ring-sky-500 shadow-sm custom-button", "aria-label": "Open AI Search" }, h("svg", { width: "24", height: "24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", class: "flex-none text-slate-300 dark:text-slate-400" }, h("path", { d: "m19 19-3.5-3.5" }), h("circle", { cx: "11", cy: "11", r: "6" })), h("span", { class: "flex-auto" }, this.pPlaceholder), h("kbd", { class: "font-sans font-semibold text-slate-400" }, h("abbr", { title: "Command", class: "no-underline text-slate-400" }, isMacOS && h("span", null, "\u2318"), !isMacOS && (h("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 16 16", fill: "currentColor", class: "inline w-4 h-4 mb-1" }, h("path", { d: "M3.5 2A1.5 1.5 0 0 0 2 3.5v2A1.5 1.5 0 0 0 3.5 7h2A1.5 1.5 0 0 0 7 5.5v-2A1.5 1.5 0 0 0 5.5 2h-2ZM3.5 9A1.5 1.5 0 0 0 2 10.5v2A1.5 1.5 0 0 0 3.5 14h2A1.5 1.5 0 0 0 7 12.5v-2A1.5 1.5 0 0 0 5.5 9h-2ZM9 3.5A1.5 1.5 0 0 1 10.5 2h2A1.5 1.5 0 0 1 14 3.5v2A1.5 1.5 0 0 1 12.5 7h-2A1.5 1.5 0 0 1 9 5.5v-2ZM10.5 9A1.5 1.5 0 0 0 9 10.5v2a1.5 1.5 0 0 0 1.5 1.5h2a1.5 1.5 0 0 0 1.5-1.5v-2A1.5 1.5 0 0 0 12.5 9h-2Z" })))), "K")));
    }
    displayMessage() {
        var _a, _b, _c, _d, _e, _f;
        let message = null;
        // let messageText = null
        if (this.error) {
            message = h("p", { class: "text-red-500" }, this.errorMsg);
        }
        else {
            if (this.isSubmitted) {
                message = (h("svg", { class: "animate-spin -ml-1 mr-3 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 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })));
            }
            else {
                if (this.dirty) {
                    message = (_b = (_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a.noResultsText) !== null && _b !== void 0 ? _b : this.pNoResultsText;
                }
                message = (_d = (_c = this.ctaSettings) === null || _c === void 0 ? void 0 : _c.helpText) !== null && _d !== void 0 ? _d : this.pHelpText;
            }
        }
        if (((_e = this.searchResults) === null || _e === void 0 ? void 0 : _e.length) > 0 || ((_f = this.chatHistory) === null || _f === void 0 ? void 0 : _f.length) > 0) {
            return null;
        }
        else {
            if (typeof message === "string") {
                return h("div", { class: "flex prose custom-msg", innerHTML: message });
            }
            else {
                return h("p", { class: "custom-msg flex" }, message);
            }
        }
    }
    render() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19;
        const style = {
            "width": ((_a = this.ctaSettings) === null || _a === void 0 ? void 0 : _a.enableMobileView) ? "100%" : (_b = this.ctaSettings) === null || _b === void 0 ? void 0 : _b.dialogWidth,
            "max-width": (_c = this.ctaSettings) === null || _c === void 0 ? void 0 : _c.dialogMaxWidth,
            "min-height": this.chatHistory.length > 0 ? "unset" : (_e = (_d = this.ctaSettings) === null || _d === void 0 ? void 0 : _d.dialogMinHeight) !== null && _e !== void 0 ? _e : "300px",
            "margin-top": (_g = (_f = this.ctaSettings) === null || _f === void 0 ? void 0 : _f.dialogTopMargin) !== null && _g !== void 0 ? _g : "5rem",
        };
        if (!this.canRender) {
            return (h(Host, null, h("span", { style: { display: "none" } }, "Failed to load ai12z control due to insufficient fund")));
        }
        return (h(Host, null, this.isRendered && (h("div", { class: "custom-container", onClick: () => this.openModal() }, !this.isCta && this.defaultTemplate(), this.isCta && h("slot", { name: "cta" }))), h("div", { class: { "bg-smoke-light": true, "modal-wrapper": true, "custom-model": true, "hide-dialog": !this.showModal }, onClick: ev => this.handleOutsideClick(ev), role: "dialog", "aria-modal": "true", "aria-label": "Search modal", "aria-describedby": ((_h = this.ctaSettings) === null || _h === void 0 ? void 0 : _h.allowClose) ? undefined : "modal-close-info" }, h("div", { "aria-live": "assertive", "aria-atomic": "true", class: "sr-only" }, this.announceMessage), !((_j = this.ctaSettings) === null || _j === void 0 ? void 0 : _j.allowClose) && (h("div", { id: "modal-close-info", class: "sr-only" }, "This dialog cannot be closed with Escape key or by clicking outside. Please complete your interaction.")), h("div", { class: "skip-links" }, h("a", { class: "skip-link", href: "#main-content", onClick: e => {
                var _a;
                e.preventDefault();
                // this.skipTo('main-content');
                const el = (_a = this.el.shadowRoot.querySelector("ai12z-chat")) === null || _a === void 0 ? void 0 : _a.shadowRoot.querySelector("#main-content");
                if (el) {
                    ;
                    el.focus();
                }
            } }, "Skip to main content"), h("a", { class: "skip-link", href: "#searchInput", onClick: e => {
                e.preventDefault();
                // this.skipTo('message-input');
                const el = this.el.shadowRoot.querySelector("ai12z-input-form").querySelector("#searchInput");
                if (el) {
                    ;
                    el.focus();
                }
            } }, "Skip to message input")), h("div", { class: "overscroll-contain modal-content-wrapper model-content  modal-position", style: style }, this.chatHistory.length > 0 && (h("span", { class: "btn-left" }, h("button", { title: "New Chat", "aria-label": "New Chat", onClick: () => {
                this.chatHistory = [];
                this.isChat = false;
                this.displayMessage();
            }, class: "modal-home" }, h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }, h("path", { d: "M21 12a9 9 0 1 1-3-6.7" }), h("polyline", { points: "21 3 21 9 15 9" }))))), h("span", { class: "btn-position" }, ((_k = this.ctaSettings) === null || _k === void 0 ? void 0 : _k.allowClose) && (h("button", { onClick: () => this.closeModal(), class: "modal-close", "aria-label": "Close AI Search", tabindex: "0", title: "Close AI Search" }, h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "1.8", "stroke-linecap": "round", "stroke-linejoin": "round" }, h("line", { x1: "18", y1: "6", x2: "6", y2: "18" }), h("line", { x1: "6", y1: "6", x2: "18", y2: "18" }))))), h("div", { class: "modal-body flex flex-col" }, h("h1", { class: "model-heading" }, (_m = (_l = this.ctaSettings) === null || _l === void 0 ? void 0 : _l.heading) !== null && _m !== void 0 ? _m : this.pheading), h("div", { class: `cta-layout flex flex-col flex-1 ${((_o = this.ctaSettings) === null || _o === void 0 ? void 0 : _o.textareaAtBottom) ? "reverse" : "normal"}` }, h("div", { class: "input-wrapper" }, h("ai12z-input-form", { onAction: async (event) => {
                const { value, type, followUp, imgFiles } = event.detail;
                await this.handleSubmit(event, value, type, followUp, imgFiles);
            }, isChat: this.isChat, componentType: "cta", chatLength: this.chatHistory.length, placeholder: (_q = (_p = this.ctaSettings) === null || _p === void 0 ? void 0 : _p.placeholder) !== null && _q !== void 0 ? _q : this.pPlaceholder, buttonText: ((_r = this.ctaSettings) === null || _r === void 0 ? void 0 : _r.buttonText)
                ? (_s = this.ctaSettings) === null || _s === void 0 ? void 0 : _s.buttonText
                : ((_t = this.ctaSettings) === null || _t === void 0 ? void 0 : _t.buttonText) == "" || !((_u = this.ctaSettings) === null || _u === void 0 ? void 0 : _u.buttonText) || (((_w = this.ctaSettings) === null || _w === void 0 ? void 0 : _w.buttonText) == "" && ((_x = this.ctaSettings) === null || _x === void 0 ? void 0 : _x.iconSrc) == "")
                    ? !((_y = this.ctaSettings) === null || _y === void 0 ? void 0 : _y.buttonText) && ((_z = this.ctaSettings) === null || _z === void 0 ? void 0 : _z.iconSrc)
                        ? ""
                        : this.pButtonText
                    : (_0 = this.ctaSettings) === null || _0 === void 0 ? void 0 : _0.buttonText, iconSrc: (_2 = (_1 = this.ctaSettings) === null || _1 === void 0 ? void 0 : _1.iconSrc) !== null && _2 !== void 0 ? _2 : "", followUpLabel: (_4 = (_3 = this.ctaSettings) === null || _3 === void 0 ? void 0 : _3.followUpLabel) !== null && _4 !== void 0 ? _4 : "Do you have a follow up question?", isImageUpload: (_6 = (_5 = this.ctaSettings) === null || _5 === void 0 ? void 0 : _5.imageUpload) !== null && _6 !== void 0 ? _6 : true, isEnableMic: (_8 = (_7 = this.ctaSettings) === null || _7 === void 0 ? void 0 : _7.enableMic) !== null && _8 !== void 0 ? _8 : true, "data-key": this.dataKey, "data-mode": this.dataMode })), h("div", { id: "main-content", class: "content-area" }, !this.showHistory && this.displayMessage(), h("div", { class: "custom-results" }, !this.isChat && !((_9 = this.ctaSettings) === null || _9 === void 0 ? void 0 : _9.categorize) && h(SearchResult, { results: this.searchResults }), !this.isChat && ((_10 = this.ctaSettings) === null || _10 === void 0 ? void 0 : _10.categorize) && h("ai12z-category", { categoryList: this.searchResults, linkTarget: (_11 = this.ctaSettings) === null || _11 === void 0 ? void 0 : _11.linkTarget })), this.isChat && (h("ai12z-chat", {
            // socket={this.socket}
            chats: this.chatHistory, env: this.dataMode, query: this.formData.search, apiKey: this.dataKey, aiMessageId: this.aiMessageId, imgFiles: this.imgFiles, target: ((_12 = this.ctaSettings) === null || _12 === void 0 ? void 0 : _12.linkTarget) === "" ? "_blank" : (_13 = this.ctaSettings) === null || _13 === void 0 ? void 0 : _13.linkTarget, voiceType: ((_14 = this.ctaSettings) === null || _14 === void 0 ? void 0 : _14.audioType) || "default", voice: ((_15 = this.ctaSettings) === null || _15 === void 0 ? void 0 : _15.voice) || "Google US English", onFeedback: async (event) => {
                const { feedback, insightId } = event.detail;
                sendFeedback(this.dataKey, this.dataMode, insightId, feedback);
            }, componentType: "ctasearch", socketIn: this.socketService, dataAttributes: this.dataAttributes, chatExcludeTags: this.excludeTags, chatIncludeTags: this.includeTags, customstyle: (_16 = this.ctaSettings) === null || _16 === void 0 ? void 0 : _16.customCSS, customJS: (_17 = this.ctaSettings) === null || _17 === void 0 ? void 0 : _17.customJS, settings: (_18 = this.ctaSettings) !== null && _18 !== void 0 ? _18 : {}
        })), this.showHistory && h("chatbot-history", { chatList: this.conversationHistory, botName: (_19 = this.ctaSettings) === null || _19 === void 0 ? void 0 : _19.name }), !this.isChat && (h("div", { class: "custom-privacy" }, h("slot", { name: "custom-privacy" }))))))))));
    }
    static get is() { return "ai12z-cta"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["./ai12z-cta.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ai12z-cta.css"]
        };
    }
    static get properties() {
        return {
            "isCta": {
                "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-cta",
                "defaultValue": "false"
            },
            "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": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "config-id"
            },
            "dataAttributes": {
                "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-attributes"
            },
            "options": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "{ [key: string]: any }",
                    "resolved": "{ [key: string]: any; }",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "{}"
            },
            "excludeTags": {
                "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": "[]"
            },
            "includeTags": {
                "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": "[]"
            }
        };
    }
    static get states() {
        return {
            "socketService": {},
            "ctaSettings": {},
            "showModal": {},
            "timer": {},
            "questionCounter": {},
            "formData": {},
            "searchResults": {},
            "error": {},
            "conversationId": {},
            "canRender": {},
            "chatHistory": {},
            "isChat": {},
            "aiMessageId": {},
            "thumbsId": {},
            "imgFiles": {},
            "announceMessage": {},
            "showHistory": {},
            "conversationHistory": {},
            "isRendered": {}
        };
    }
    static get events() {
        return [{
                "method": "errored",
                "name": "errored",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "buttonClicked",
                "name": "buttonClicked",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "messageSent",
                "name": "messageSent",
                "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": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "open",
                "name": "open",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "close",
                "name": "close",
                "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": "clearResults",
                "name": "clearResults",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "clearInput",
                "name": "clearInput",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "stopStream",
                "name": "stopStream",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "startStream",
                "name": "startStream",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ search: string; maxQuestion?: boolean; chatData?: any; attributes?: any; imgFiles?: any }",
                    "resolved": "{ search: string; maxQuestion?: boolean; chatData?: any; attributes?: any; imgFiles?: any; }",
                    "references": {}
                }
            }, {
                "method": "survey",
                "name": "survey",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "formSubmitted",
                "name": "formSubmitted",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "streamResponse",
                "name": "streamResponse",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "endResponse",
                "name": "endResponse",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "isElementAvailable",
                "name": "isElementAvailable",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "openModal": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "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: any, displayText: string) => Promise<void>",
                    "parameters": [{
                            "name": "jsonData",
                            "type": "any",
                            "docs": ""
                        }, {
                            "name": "displayText",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "closeModal": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "dataKey",
                "methodName": "onDataKeyChange"
            }, {
                "propName": "dataMode",
                "methodName": "onDataModeChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "keydown",
                "method": "handleKeyDown",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "survey",
                "method": "surveyHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "formComplete",
                "method": "formSubmittedHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "deleteChatHistory",
                "method": "deleteChatHistoryHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "chatClick",
                "method": "chatClickHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
