import { r as registerInstance, a as createEvent, E as Env, e as ai12zManager, h, f as Host, d as getElement } from './index-BNpVu1WU.js';
import { P as search, e as insertStyles, J as checkStatus, L as getConfig, p as sendFeedback } from './utils-DK_Yhmpx.js';
import { S as SearchResult } from './SearchResult-zLaEhc3L.js';
import { S as SocketService } from './socket-service-D_h5x8Gr.js';
import { b as setCtaElement } from './global-store-odmyXuxx.js';
import { e as executeRecaptcha } from './reCaptchaHelpers-DUpCzUFb.js';
import { d as detectLanguage, l as loadLanguageFile, a as getConversationHistory, f as filterConversationHistoryByProjectAndConfig, b as setLocalData, r as removeLastMessage, v as validateFormInput, c as createChatMessage, g as generateUUID, u as updateChatHistory, i as isMaxQuestionsReached, e as clearTimer, h as isOutsideClick, j as createAutoResetTimer, k as insertCustomJS, m as insertCustomCSS, n as isMac } from './ctaHelpers-DrH6S5iU.js';
import { a as setParentComponentState } from './app-store-DYN4CiXV.js';
import './response-adapter-SyQT2Pr3.js';

const ai12zCtaCss = () => `:host{--bg-smoke-light:rgba(0, 0, 0, 0.5);margin-left:20px;font-family:var(--ai12z-search-font-family) var(--ai12z-font-family) !important;font-size:var(--ai12z-search-font-size, var(--ai12z-font-size)) !important;color:var(--ai12z-font-color, black);text-align:var(--ai12z-text-align, left)}.keyboard-shortcuts-btn{vertical-align:middle;padding-right:5px;color:#666}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.skip-links{position:relative;z-index:9999}.skip-link{position:absolute;top:-40px;left:0;background-color:var(--ai12z-primary-color, #007bff);color:white;padding:8px 16px;text-decoration:none;border-radius:4px;font-weight:500;z-index:10000;opacity:0;pointer-events:none;transition:top 0.2s, opacity 0.2s}.skip-link:focus{top:8px;opacity:1;pointer-events:auto;outline:3px solid var(--ai12z-secondary-accent, #0056b3);outline-offset:2px}.bg-smoke-light{transition:opacity 300ms ease-in-out;position:fixed;top:0;left:0;z-index:200;height:100vh;width:100vw;cursor:auto;flex-direction:column;background-color:#0003;--tw-backdrop-blur:blur(4px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate)     var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.modal-content{transition:transform 300ms ease-in-out,     opacity 300ms ease-in-out;transform:scale(0.9);opacity:0}.modal-position{position:relative;padding:2rem 1rem 0.5rem 1rem;flex-direction:column}.modal-close:hover{color:rgb(31 41 55)}.model-heading{color:var(--ai12z-heading-color);font-size:var(--ai12z-heading-font-size)}:host(.show-modal) .bg-smoke-light{opacity:1}:host(.show-modal) .modal-content{transform:scale(1);opacity:1}.modal-content-wrapper{background-color:rgb(255 255 255);width:100%;max-width:48rem;border-radius:0.5rem;}.model-wrapper{position:fixed;top:0;left:0;z-index:200;height:100vh;width:100vw;cursor:auto;flex-direction:column;background-color:#0003;padding:1rem;--tw-backdrop-blur:blur(4px);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate)     var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.custom-model{overflow:auto;inset:0px;position:fixed;min-height:100vh;display:flex;align-items:center;justify-items:center}.hide-dialog{display:none !important}.modal-position .btn-position{position:absolute;right:0px;top:0px;padding:0.25rem 1rem;color:var(--ai12z-secondary-accent, #0056B3)}@media (max-width: 768px){.modal-content-wrapper{width:100%;height:100vh;height:100svh !important;margin:0 !important;border-radius:0;overflow:auto}.custom-privacy{position:fixed !important;bottom:0;left:0;width:100%;padding:10px}.modal-position .btn-position{padding:0.45rem 0.75rem 0.45rem 1rem;position:fixed}.content-area{padding:0px !important}}.btn-left{top:0;left:0;position:absolute;padding:0.35rem 1rem;color:var(--ai12z-secondary-accent, #0056B3)}.custom-privacy{color:var(--ai12z-knowledge-box-privacy-color);text-align:center;margin-top:auto;bottom:0;left:0;right:0}.custom-button{align-items:center;text-align:left;background-color:rgb(255 255 255);color:rgb(148 163 184);border-radius:0.5rem;width:18rem;min-height:3rem;padding-left:1rem;padding-right:1rem;}.custom-msg{text-align:center;color:var(--ai12z-font-mute);justify-content:center;max-width:none !important;}.cta-search-results{border-top-width:1px;border-bottom-width:0px;border-color:rgb(243 244 246)}.cta-search-results-list{position:relative;padding-bottom:1.25rem;padding-top:1.25rem}.cta-search-results-list:hover{background-color:var(--ai12z-hover-bg-color)}.cta-search-container{margin-left:auto;margin-right:auto;display:flex;max-width:56rem;justify-content:space-between;-moz-column-gap:1.5rem;column-gap:1.5rem}.cta-search-container-two{display:flex;min-width:0px;-moz-column-gap:1rem;column-gap:1rem}.cta-search-container-three{min-width:0px;flex:1 1 auto}.cta-search-text{font-weight:600;line-height:1.5rem;font-size:var(--ai12z-search-result-title-font-size);color:var(--ai12z-search-result-title-color)}.cta-search-text-position{position:absolute;left:0px;right:0px;top:-1px;bottom:0px}.cta-search-description{margin-top:0.25rem;display:flex;font-size:var(--ai12z-search-result-description-font-size);line-height:1rem;line-height:1.25rem;color:var(--ai12z-search-result-description-color)}.cta-search-list-arrow{display:flex;align-items:center;flex-shrink:0;-moz-column-gap:1rem;column-gap:1rem}.custom-icon-width{width:4rem}.results-icon svg{width:1.5rem;height:1.5rem}.modal-body{display:flex;flex-direction:column}.cta-layout{display:flex;flex:1;min-height:0}.cta-layout.normal{flex-direction:column}.cta-layout.reverse{flex-direction:column-reverse}.input-wrapper{position:sticky;top:0;bottom:0;z-index:10;background:white;padding:1rem}.content-area{flex:1;padding:0.75rem}`;

const Ai12zCta = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.errored = createEvent(this, "errored", 7);
        this.buttonClicked = createEvent(this, "buttonClicked", 7);
        this.messageSent = createEvent(this, "messageSent", 7);
        this.messageReceived = createEvent(this, "messageReceived", 7);
        this.open = createEvent(this, "open", 7);
        this.close = createEvent(this, "close", 7);
        this.stateChanged = createEvent(this, "stateChanged", 7);
        this.clearResults = createEvent(this, "clearResults", 7);
        this.clearInput = createEvent(this, "clearInput", 7);
        this.stopStream = createEvent(this, "stopStream", 7);
        this.startStream = createEvent(this, "startStream", 7);
        this.survey = createEvent(this, "survey", 7);
        this.formSubmitted = createEvent(this, "formSubmitted", 7);
        this.streamResponse = createEvent(this, "streamResponse", 7);
        this.endResponse = createEvent(this, "endResponse", 7);
        this.isElementAvailable = createEvent(this, "isElementAvailable", 7);
        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" }))))))))));
    }
    get el() { return getElement(this); }
    static get watchers() { return {
        "dataKey": [{
                "onDataKeyChange": 0
            }],
        "dataMode": [{
                "onDataModeChange": 0
            }]
    }; }
};
Ai12zCta.style = ai12zCtaCss();

export { Ai12zCta as ai12z_cta };
