import { h, Env } from "@stencil/core";
import { search, generateUUID, sendFeedback, getConfig, insertStyles } from "../../utils/utils";
import SearchResult from "../ai12z-cta/components/SearchResult";
import { SocketService } from "../../utils/socket-service";
import { createAutoResetTimer, insertCustomCSS, insertCustomJS, isMaxQuestionsReached, setLocalData } from "../../utils/ctaHelpers";
import { setSearchResultsElement } from "../../utils/global-store";
import { ai12zManager } from "../../utils/ai12z-manager";
import { executeRecaptcha } from "../../utils/botHelpers/reCaptchaHelpers";
export class SearchResultsPage {
    constructor() {
        this.cdnPath = "https://cdn.ai12z.net/assets/cta";
        this.dataKey = Env.DATA_KEY || "";
        this.dataMode = Env.DATA_MODE || "prod";
        this.query = "";
        this.searchResultSettings = {};
        this.searchResults = [];
        this.hideAllButtons = false;
        this.isChat = false;
        this.chatHistory = [];
        this.aiMessageId = null;
        this.thumbsId = null;
        this.isOpen = false;
        this.capturedFile = null;
        this.imgFiles = [];
        this.displayText = "";
        this.questionCounter = 0;
        this.emptyMessageError = false;
        this.announceMessage = "";
        this.isRendered = false;
        this.imagesBase64List = [];
        this.handleKeyDown = (event) => {
            // if (event.key === "Enter" && event.shiftKey) {
            // console.log("Shift + Enter detected")
            // Prevent default behavior if needed
            // }
            if (event.key === "Enter" && !event.shiftKey) {
                event.preventDefault();
                if ((this.query && this.query.trim().length > 0) || this.imagesBase64List.length > 0) {
                    this.handleFormSubmit(event);
                }
                else {
                    // Show error when Enter is pressed with empty message
                    this.emptyMessageError = true;
                    if (this.searchInputElem) {
                        this.searchInputElem.focus();
                    }
                    setTimeout(() => {
                        this.emptyMessageError = false;
                    }, 3000);
                }
            }
        };
        this.adjustHeight = () => {
            this.searchInputElem.style.height = "auto";
            this.searchInputElem.style.height = this.searchInputElem.scrollHeight + "px";
        };
        this.toggleBox = e => {
            e.stopPropagation();
            this.isOpen = !this.isOpen;
        };
        this.handleClickOutside = (event) => {
            const target = event.target;
            if (this.isOpen && this.menuElem && !this.menuElem.contains(target)) {
                this.isOpen = false;
            }
        };
    }
    async fetchSearchResults() {
        const response = await search(this.dataKey, this.dataMode, this.query);
        const newResults = response.docs ? [...response.docs] : [];
        this.searchResults = []; // Reset to trigger reactivity
        setTimeout(() => {
            this.searchResults = newResults;
            // console.log("searchResults", this.searchResults)
        }, 0);
    }
    messageReceivedHandler(_state) {
        if (_state.detail && _state.detail.data.context && _state.detail.data.context.length > 0 && this.searchResultSettings.autoSearch) {
            this.searchResults = _state.detail.data.context || [];
        }
    }
    async sendMessage(message, displayText) {
        this.query = displayText !== null && displayText !== void 0 ? displayText : message;
        this.handleFormSubmit(new SubmitEvent("submit"));
        this.messageSent.emit(message);
    }
    async sendJSON(jsonData, displayText) {
        this.displayText = displayText;
        this.query = jsonData;
        this.handleFormSubmit(new SubmitEvent("submit"));
        this.messageSent.emit(jsonData);
    }
    async configSearchSettings() {
        var _a, _b, _c, _d;
        const payload = {
            apiKey: this.dataKey,
            configId: this.configId,
            configType: "searchResult",
        };
        try {
            const data = await getConfig(payload, this.dataMode);
            // console.log("data", data)
            if (data) {
                // console.log("Web Settings", data)
                this.searchResultSettings = data;
                if ((_a = data === null || data === void 0 ? void 0 : data.v3) === null || _a === void 0 ? void 0 : _a.siteKey) {
                    try {
                        const response = await executeRecaptcha(data._id, data.v3.siteKey, "searchResult", this.dataKey, this.dataMode, detail => {
                            this.errored.emit(detail);
                        });
                        this.isRendered = !!response;
                    }
                    catch (err) {
                        console.error("Recaptcha verification failed:", err);
                        this.isRendered = false;
                    }
                }
                else {
                    this.isRendered = true;
                }
                if (((_b = this.searchResultSettings) === null || _b === void 0 ? void 0 : _b.autoSearch) === undefined) {
                    this.searchResultSettings.autoSearch = true;
                }
                if (this.searchResultSettings.theme) {
                    let themeLink = "";
                    if (this.searchResultSettings.theme !== "custom") {
                        themeLink = `${this.cdnPath}/v2/themes/theme-${this.searchResultSettings.theme}.css`;
                    }
                    else {
                        themeLink = this.searchResultSettings.customTheme;
                    }
                    const linkEl = document.createElement("link");
                    linkEl.setAttribute("rel", "stylesheet");
                    linkEl.setAttribute("href", themeLink);
                    document.head.appendChild(linkEl);
                }
                if (((_c = this.searchResultSettings) === null || _c === void 0 ? void 0 : _c.categorize) === undefined) {
                    this.searchResultSettings.categorize = true;
                }
                if (this.searchResultSettings.customCSS) {
                    this.insertCustomCSS(this.searchResultSettings.customCSS);
                }
                // ✅ Load welcome assets and wait for them
                if (this.searchResultSettings.welcome) {
                    this.invokeWelcomeAssets();
                }
                if (this.searchResultSettings.customJS) {
                    const scriptEl = document.createElement("script");
                    scriptEl.setAttribute("type", "text/javascript");
                    scriptEl.setAttribute("src", this.searchResultSettings.customJS);
                    (_d = this.el.shadowRoot) === null || _d === void 0 ? void 0 : _d.appendChild(scriptEl);
                }
                if (this.searchResultSettings.hasOwnProperty("inputFieldPosition")) {
                    this.searchResultSettings.textareaAtBottom = this.searchResultSettings.inputFieldPosition === "bottom" ? true : false;
                }
                else {
                    this.searchResultSettings.textareaAtBottom = false;
                }
            }
        }
        catch (error) {
            console.error("Error loading configuration:", error);
        }
    }
    async invokeWelcomeAssets() {
        await this.loadWelcomeAssets();
    }
    insertCustomCSS(css) {
        // console.log("css", css)
        const linkEl = document.createElement("link");
        linkEl.setAttribute("rel", "stylesheet");
        linkEl.setAttribute("href", css);
        const shadowRoot = this.el.shadowRoot;
        if (shadowRoot) {
            shadowRoot.appendChild(linkEl);
        }
    }
    async componentWillLoad() {
        insertStyles(`https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css`, this.el);
        // Get the query string from the URL
        const urlParams = new URLSearchParams(window.location.search);
        // Extract individual query parameters
        this.query = urlParams.get("searchText"); // 'StencilJS'
        await this.configSearchSettings();
        document.addEventListener("click", this.handleClickOutside);
    }
    async componentDidLoad() {
        setSearchResultsElement(this.el);
        ai12zManager.register("ai12z-search-results-page", this);
        ai12zManager.setActive("ai12z-search-results-page");
        // console.log("componentWillRender")
        if (this.query && this.query.length > 0) {
            const inputElement = this.el.shadowRoot.querySelector("#search-input");
            if (inputElement) {
                const event = new InputEvent("input", { bubbles: true });
                Object.defineProperty(event, "target", { writable: false, value: inputElement });
                inputElement.value = this.query;
                if (this.searchResultSettings.loadResults && this.query.length > 3) {
                    await this.fetchSearchResults();
                    this.handleFormSubmit(new SubmitEvent("submit"));
                    // this.handleInput(event) // Call manually
                }
                else {
                    this.handleFormSubmit(new SubmitEvent("submit"));
                }
                inputElement.dispatchEvent(event);
            }
        }
    }
    disconnectedCallback() {
        // Clean up event listeners to avoid memory leaks
        document.removeEventListener("click", this.handleClickOutside);
        // Remove any other cleanup logic if necessary
    }
    surveyHandler(_state) {
        // console.log("surveyHandler", _state.detail)
        //this.handleSubmit(null, _state.detail.results, _state.detail.type, false, null)
        if (_state.detail.type === "button") {
            this.query = _state.detail.results;
            this.handleFormSubmit(new SubmitEvent("submit"));
            // 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 = [...this.chatHistory.slice(0, idx), _state.detail.results, ...this.chatHistory.slice(idx + 1)];
        }
        else if (_state.detail.type === "sendMessage") {
            // console.log("sendMessage", _state.detail.results)
            if (_state.detail.results.length > 1) {
                this.displayText = _state.detail.results[1];
                this.query = _state.detail.results[0];
                this.handleFormSubmit(new SubmitEvent("submit"));
                // this.sendMessage(_state.detail.results[0], _state.detail.results[1])
            }
            else {
                this.query = _state.detail.results[0];
                this.handleFormSubmit(new SubmitEvent("submit"));
                // this.sendMessage(_state.detail.results[0])
            }
        }
        else if (_state.detail.type === "sendJSON") {
            this.displayText = _state.detail.results[1];
            this.query = _state.detail.results[0];
            this.handleFormSubmit(new SubmitEvent("submit"));
            // this.sendJSON(_state.detail.results[0], _state.detail.results[1])
        }
        else {
            // this.sendSurveyData(_state.detail)
            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.query = jsonData;
            this.displayText = surveyData.completeText;
            this.handleFormSubmit(new SubmitEvent("submit"), { isHide: true });
        }
    }
    async handleInput(event) {
        const target = event.target;
        this.query = target.value;
        if (this.query.trim().length > 3) {
            if (this.searchResultSettings.autoSearch) {
                // if (this.searchResultSettings.autoSearch && !this.isChat) {
                this.fetchSearchResults();
                // this.showWelcomeTemplate = false
            }
        }
        else if (!this.isChat) {
            this.showWelcomeTemplate = true;
            this.searchResults = [];
            return;
        }
    }
    // ✅ Dedicated method to load welcome assets
    async loadWelcomeAssets() {
        var _a, _b;
        const promises = [];
        // Load styles
        if ((_a = this.searchResultSettings.welcome) === null || _a === void 0 ? void 0 : _a.styles) {
            const stylePromise = new Promise(resolve => {
                insertCustomCSS(this.el.shadowRoot, this.searchResultSettings.welcome.styles);
                // Give CSS time to apply
                setTimeout(resolve, 100);
            });
            promises.push(stylePromise);
        }
        // Load scripts
        if ((_b = this.searchResultSettings.welcome) === null || _b === void 0 ? void 0 : _b.scripts) {
            const scriptPromise = new Promise(resolve => {
                insertCustomJS(this.el.shadowRoot, this.searchResultSettings.welcome.scripts);
                // Give JS time to execute
                setTimeout(resolve, 200);
            });
            promises.push(scriptPromise);
        }
        // Wait for all assets to load
        await Promise.all(promises);
        // ✅ Show welcome template immediately if no query
        if (!this.query || this.query.length === 0) {
            this.showWelcomeTemplate = true;
        }
    }
    startTimer() {
        var _a;
        this.timer = createAutoResetTimer(() => {
            this.questionCounter = 0;
            setLocalData(`ai12z-search-result-data`, { qCounter: this.questionCounter });
        }, (_a = this.searchResultSettings) === null || _a === void 0 ? void 0 : _a.autoResetTimer);
    }
    announce(message) {
        this.announceMessage = message;
        setTimeout(() => {
            this.announceMessage = "";
        }, 1000);
    }
    async handleFormSubmit(event, options) {
        var _a, _b, _c;
        // console.log("handleFormSubmit", event)
        event.stopPropagation();
        event.preventDefault();
        // const response = await search(this.dataKey, this.dataMode, this.query)
        // console.log(response)
        // this.searchResults = response.docs || []
        if ((!this.query || this.query.trim().length === 0) && this.imagesBase64List && this.imagesBase64List.length < 1) {
            // Show error for empty message
            this.emptyMessageError = true;
            if (this.searchInputElem) {
                this.searchInputElem.focus();
            }
            setTimeout(() => {
                this.emptyMessageError = false;
            }, 3000);
            return;
        }
        this.emptyMessageError = false;
        this.announce("Message sent successfully");
        this.showWelcomeTemplate = false;
        this.isChat = true;
        if (this.isChat) {
            this.questionCounter++;
            setLocalData(`ai12z-search-result-data`, { qCounter: this.questionCounter });
        }
        if (this.chatHistory.length === 0 && ((_a = this.searchResultSettings) === null || _a === void 0 ? void 0 : _a.autoResetTimer) > 0 && this.isChat) {
            this.startTimer();
        }
        if (this.chatHistory.length === 0 && !this.socketService) {
            this.socketService = SocketService.createInstance(this.dataMode, this.dataKey);
            // Wait for socket connection before proceeding
            await this.socketService.waitForConnection();
        }
        // this.aiMessageId = `ai-message-${generateUUID()}`
        try {
            let response = { answer: "", formModel: null, insight_id: null };
            this.chatHistory.push({
                message: this.displayText ? this.displayText : this.query,
                images: this.imagesBase64List,
                status: "success",
                type: "user",
                isHide: (options === null || options === void 0 ? void 0 : options.isHide) || false,
            });
            this.imgFiles = this.imagesBase64List.length > 0 ? this.imagesBase64List : [];
            response.answer =
                ((_b = this.searchResultSettings) === null || _b === void 0 ? void 0 : _b.maxQuestion) > 0 && this.questionCounter > ((_c = this.searchResultSettings) === null || _c === void 0 ? void 0 : _c.maxQuestion) ? this.searchResultSettings.msgLimit : response === null || response === void 0 ? void 0 : response.answer;
            // this.aiMessageId = `ai-message-${generateUUID()}`
            this.aiMessageId = "";
            this.thumbsId = generateUUID();
            this.chatHistory.push({
                message: `<div class="animate-ping">...</div>`,
                type: "ai",
                status: "pending",
                id: this.aiMessageId,
            });
            this.chatHistory.pop();
            const lastMessage = {
                message: response === null || response === void 0 ? void 0 : response.answer,
                type: "ai",
                status: "success",
                insightId: response === null || response === void 0 ? void 0 : response.insight_id,
                id: this.aiMessageId,
                thumbsId: this.thumbsId,
                formModel: response === null || response === void 0 ? void 0 : response.formModel,
                isLoading: true,
            };
            this.chatHistory = [...this.chatHistory, lastMessage];
            // console.log("chatHistory", this.query)
            requestAnimationFrame(() => {
                requestAnimationFrame(() => {
                    var _a;
                    if (isMaxQuestionsReached(this.questionCounter, (_a = this.searchResultSettings) === null || _a === void 0 ? void 0 : _a.maxQuestion)) {
                        // console.log("Max question limit reached on cta")
                        this.chatHistory[this.chatHistory.length - 1].id = `chatbot-${generateUUID()}`;
                        this.startStream.emit({ search: this.query, maxQuestion: true, chatData: this.chatHistory[this.chatHistory.length - 1] });
                    }
                    else {
                        // console.log("type", typeof this.formData.search)
                        this.startStream.emit({ search: this.query, imgFiles: this.imgFiles });
                    }
                });
            });
            setTimeout(() => {
                this.query = "";
                this.displayText = "";
                this.searchInputElem.value = "";
                this.imagesBase64List = [];
                const parent = this.el.shadowRoot.querySelector("#previewContainer");
                if (parent) {
                    parent.innerHTML = "";
                }
                this.adjustHeight();
            }, 1000);
        }
        catch (error) {
            console.error("Error:", error);
        }
        finally {
            // this.query = ""
            // this.searchInputElem.value = ""
        }
    }
    onInputChange(files) {
        // this.showErrorMessage = false
        if (files.length > 0) {
            this.uploadImage(files);
        }
        else {
            console.error(files.length === 0 || "NO IMAGE UPLOADED");
            return false;
        }
    }
    uploadImage(files) {
        let newFile;
        let tempImagesBase64List = [];
        if (files.length > 10 || this.imagesBase64List.length > 10) {
            // this.showErrorMessage = true
            // console.error('You can upload a maximum of 10 images once at a time.');
            return;
        }
        for (var i = 0; i < files.length; i++) {
            const mimeType = files[i].type;
            if (!mimeType.match("image.*")) {
                // console.log("file is not an image")
                return;
            }
            newFile = files[i];
            const reader = new FileReader();
            reader.onload = () => {
                const imagePreviewContainer = this.el.shadowRoot.querySelector("#previewContainer");
                const base64Image = `data:${mimeType};base64,${reader.result.split(",")[1]}`;
                this.imagesBase64List.push(base64Image);
                tempImagesBase64List = this.imagesBase64List;
                const newDiv = document.createElement("div");
                newDiv.classList.add("image-Container");
                newDiv.classList.add("sc-ai12z-input-form");
                const img = document.createElement("img");
                img.setAttribute("src", reader.result);
                img.style.width = "70px";
                img.style.height = "50px";
                img.style.borderRadius = ".75rem";
                const deleteSpan = document.createElement("span");
                deleteSpan.textContent = "x";
                deleteSpan.classList.add("delete-image");
                deleteSpan.classList.add("sc-ai12z-input-form");
                imagePreviewContainer.appendChild(newDiv);
                newDiv.appendChild(img);
                newDiv.appendChild(deleteSpan);
                deleteSpan.onclick = event => {
                    let imgSrc = event.target["previousSibling"] ? event.target["previousSibling"].src : null;
                    let index = tempImagesBase64List.indexOf(imgSrc);
                    if (index > -1) {
                        tempImagesBase64List.splice(index, 1);
                    }
                    if (tempImagesBase64List.length < 10) {
                        // this.showErrorMessage = false
                    }
                    newDiv.remove();
                };
                // console.log('uploading finished, emitting an image blob to the outside world');
            };
            reader.readAsDataURL(newFile);
            reader.onloadend = () => {
                // console.log("upload finished")
            };
            reader.onerror = err => {
                console.error("something went wrong...", err);
            };
        }
    }
    async captureScreen() {
        try {
            const stream = await navigator.mediaDevices.getDisplayMedia({
                video: true, // Capture the screen
            });
            const video = document.createElement("video");
            video.srcObject = stream;
            video.autoplay = true;
            document.body.appendChild(video); // Add temporarily to allow rendering
            // // Ensure the page stays in focus
            // document.body.focus()
            await new Promise(resolve => (video.onloadedmetadata = resolve));
            // Ensure the video is playing before capturing
            await new Promise(resolve => setTimeout(resolve, 500));
            const canvas = document.createElement("canvas");
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            const ctx = canvas.getContext("2d");
            if (ctx) {
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                // Convert canvas to Blob
                canvas.toBlob(blob => {
                    if (blob) {
                        const file = new File([blob], `screenshot-${Date.now()}.png`, { type: "image/png" });
                        this.capturedFile = file;
                        // console.log("Captured File:", file)
                        this.uploadImage([file]); // Call the uploadImage method with the captured file
                    }
                }, "image/png");
            }
            // Stop video stream after capture
            stream.getTracks().forEach(track => track.stop());
            // Remove the video element from the DOM
            document.body.removeChild(video);
        }
        catch (err) {
            console.error("Error capturing screen:", err);
        }
    }
    handleFollowUp(_event) {
        this.chatHistory = [];
        this.isChat = false;
        this.showWelcomeTemplate = true;
    }
    render() {
        var _a, _b, _c, _d, _e, _f, _g;
        return (h("div", { key: 'ec064aedbd7df60d7c691d3a4a76488a37118747', class: "flex w-full" }, this.isRendered && (h("div", { key: '5cbc8b431d3efccedb34a2a030ff913eece4a78d', class: "search-layout" }, h("div", { key: '5b0a20311ef081fd4b5a0b1d8a2b71815359084a', class: "left-column" }, h("div", { key: 'cb58944fb5f951361277ec7e09632abba83ca6c3', class: `flex flex-col relative h-full`, id: "searchPanel" }, h("fieldset", { key: 'd5c28ccfef8d93ccfddd064873dbea24ac8e21b3', class: `chat-fieldset ${this.searchResultSettings.textareaAtBottom ? "order-2" : "order-1"}`, style: this.searchResultSettings.textareaAtBottom ? { position: "sticky", bottom: "0", zIndex: "1000" } : { position: "sticky", top: "0", zIndex: "1000" } }, h("form", { key: 'fa8fcd7a5b80a96496ab758fa50f1ea4200e4352', class: "flex flex-col rounded-2xl p-2.5 search-page-container", id: "searchForm" }, h("div", { key: '4e91c1706e40cb05b2a1ad3ad7ab002c910469dc', class: "flex" }, h("div", { key: 'db7eea833f3c26902fa13bfc9fdeebbaa0f4328d', class: "flex items-center justify-between" }, !this.hideAllButtons && (this.searchResultSettings.enableAttachment || this.searchResultSettings.clearMemory) && (h("div", { key: '484c11bff7f17a9920e8a75914dd7b96fdb4b86e', class: "relative inline-block", style: { width: "5%" } }, h("button", { key: '2c91b160c432564cfb5e9279cbbdbafc4d6dfd33', class: "plus-icon chat-btn-primary", "aria-label": "Add Options", title: "Add images or capture screen", tabindex: "0", onClick: e => {
                e.stopPropagation();
                e.preventDefault();
                this.toggleBox(e);
            } }, h("svg", { key: 'f876743296e6c9f29731551d6e60780d2d95a4d4', xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", width: "20", height: "20" }, h("path", { key: 'ed87dd9ea50ced5010a92773e81e250cecc7798d', d: "M10.75 4.75a.75.75 0 0 0-1.5 0v4.5h-4.5a.75.75 0 0 0 0 1.5h4.5v4.5a.75.75 0 0 0 1.5 0v-4.5h4.5a.75.75 0 0 0 0-1.5h-4.5v-4.5Z" }))), h("div", { key: '27814d695edee9426b5bd2e46abc0e983ce2da9b', class: `absolute left-0 ${this.searchResultSettings.textareaAtBottom ? "bottom-full mb-1" : "top-full mt-1"} w-48 bg-white rounded-lg shadow-lg transition-all duration-300 ease-in-out 
                              ${this.isOpen ? "opacity-100 scale-100 pointer-events-auto" : "opacity-0 scale-90 pointer-events-none"}`, style: { zIndex: "1001" }, ref: el => (this.menuElem = el) }, h("ul", { key: '3c2ae5dbaf9503d2df42f05378abf90fbddd4df6', class: "space-y-2" }, this.searchResultSettings.enableAttachment && (h("li", { key: 'd12d4418a7c8ab66c66537420074c0e4e1ff8eab', class: "px-4 py-2 hover:bg-gray-100 cursor-pointer flex", onClick: () => {
                this.uploadImageEle.click();
                this.isOpen = false;
            } }, h("input", { key: 'ae8bd139701e297c9d7e7e8e3c92bdd455ca94fd', type: "file", multiple: true, name: "files[]", id: "fileInput", accept: "image/*", class: "hidden image-upload__input", onChange: ($event) => {
                this.onInputChange($event.target.files);
            }, ref: el => (this.uploadImageEle = el) }), h("div", { key: '5e964e9a5058284ee6733bc8d5173cc0a290dcae', class: "mr-1" }, h("svg", { key: '69f473fb93855c19cba439b248d2d45b6fcdb51b', width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", class: "h-5 w-5 shrink-0" }, h("path", { key: 'f3e1900b6a95611f32849de6b36f72f7e3e4d82f', "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M18.0322 5.02393C17.7488 5.00078 17.3766 5 16.8 5H11.5002C11.3 6 11.0989 6.91141 10.8903 7.85409C10.7588 8.44955 10.6432 8.97304 10.3675 9.41399C10.1262 9.80009 9.80009 10.1262 9.41399 10.3675C8.97304 10.6432 8.44955 10.7588 7.85409 10.8903C7.81276 10.8994 7.77108 10.9086 7.72906 10.9179L5.21693 11.4762C5.1442 11.4924 5.07155 11.5001 5 11.5002V16.8C5 17.3766 5.00078 17.7488 5.02393 18.0322C5.04612 18.3038 5.0838 18.4045 5.109 18.454C5.20487 18.6422 5.35785 18.7951 5.54601 18.891C5.59546 18.9162 5.69617 18.9539 5.96784 18.9761C6.25118 18.9992 6.62345 19 7.2 19H10C10.5523 19 11 19.4477 11 20C11 20.5523 10.5523 21 10 21H7.16144C6.6343 21 6.17954 21 5.80497 20.9694C5.40963 20.9371 5.01641 20.8658 4.63803 20.673C4.07354 20.3854 3.6146 19.9265 3.32698 19.362C3.13419 18.9836 3.06287 18.5904 3.03057 18.195C2.99997 17.8205 2.99998 17.3657 3 16.8385L3 11C3 8.92477 4.02755 6.93324 5.4804 5.4804C6.93324 4.02755 8.92477 3 11 3L16.8385 3C17.3657 2.99998 17.8205 2.99997 18.195 3.03057C18.5904 3.06287 18.9836 3.13419 19.362 3.32698C19.9265 3.6146 20.3854 4.07354 20.673 4.63803C20.8658 5.01641 20.9371 5.40963 20.9694 5.80497C21 6.17954 21 6.6343 21 7.16144V10C21 10.5523 20.5523 11 20 11C19.4477 11 19 10.5523 19 10V7.2C19 6.62345 18.9992 6.25118 18.9761 5.96784C18.9539 5.69617 18.9162 5.59546 18.891 5.54601C18.7951 5.35785 18.6422 5.20487 18.454 5.109C18.4045 5.0838 18.3038 5.04612 18.0322 5.02393ZM5.28014 9.41336L7.2952 8.96556C8.08861 8.78925 8.24308 8.74089 8.35381 8.67166C8.48251 8.59121 8.59121 8.48251 8.67166 8.35381C8.74089 8.24308 8.78925 8.08861 8.96556 7.2952L9.41336 5.28014C8.51014 5.59289 7.63524 6.15398 6.89461 6.89461C6.15398 7.63524 5.59289 8.51014 5.28014 9.41336ZM17 15C17 14.4477 17.4477 14 18 14C18.5523 14 19 14.4477 19 15V17H21C21.5523 17 22 17.4477 22 18C22 18.5523 21.5523 19 21 19H19V21C19 21.5523 18.5523 22 18 22C17.4477 22 17 21.5523 17 21V19H15C14.4477 19 14 18.5523 14 18C14 17.4477 14.4477 17 15 17H17V15Z", fill: "currentColor" }))), h("div", { key: 'f99fd5a9548e8c8a6b83fd7293f8eeeacdfb8ca6' }, "Upload Images"))), this.searchResultSettings.clearMemory && (h("li", { key: '9fbd7e0b3bcf9b4cd314c8c2235f33c2d9aeb243', class: "px-4 py-2 hover:bg-gray-100 cursor-pointer flex", onClick: e => {
                this.handleFollowUp(e);
                this.toggleBox(e);
            } }, h("div", { key: '7a2a5fad78711df38cf5f6340147d8141001b169', class: "mr-1" }, h("svg", { key: '7a2fda7c20e1e69c5df81a30b7ea2c756cc0fab9', xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", width: "20", height: "20" }, h("path", { key: '9d23f382aa01099f85ac29fc32f0b3a0d8d1c601', "fill-rule": "evenodd", d: "M4.755 10.059a7.5 7.5 0 0 1 12.548-3.364l1.903 1.903h-3.183a.75.75 0 1 0 0 1.5h4.992a.75.75 0 0 0 .75-.75V4.356a.75.75 0 0 0-1.5 0v3.18l-1.9-1.9A9 9 0 0 0 3.306 9.67a.75.75 0 1 0 1.45.388Zm15.408 3.352a.75.75 0 0 0-.919.53 7.5 7.5 0 0 1-12.548 3.364l-1.902-1.903h3.183a.75.75 0 0 0 0-1.5H2.984a.75.75 0 0 0-.75.75v4.992a.75.75 0 0 0 1.5 0v-3.18l1.9 1.9a9 9 0 0 0 15.059-4.035.75.75 0 0 0-.53-.918Z", "clip-rule": "evenodd" }))), h("div", { key: '19cf3b291617cb9014e7173800e23ba5ee78ceb1' }, "Start Over")))))))), !this.hideAllButtons && (h("div", { key: '56282475cb3514d5680be227df1a3be774a29ec8', class: "w-full mt-1 search-input-container" }, h("div", { key: '815287ba90d69de149483aeeb313624a54cb8c9d', id: "previewContainer", class: "preview-container" }), h("label", { key: '7b158ad429a5fdad3f79d1e91f4e43363264cff6', htmlFor: "search-input", class: "sr-only" }, "Your message"), h("textarea", { key: '9d1c9f3b95fcfd6fcfc71624571430c8d6661e2d', id: "search-input", "aria-describedby": this.emptyMessageError ? "search-message-error search-hint" : "search-hint", "aria-invalid": this.emptyMessageError, class: `bg-inherit w-full outline-none resize-none ${((_a = this.searchResults) === null || _a === void 0 ? void 0 : _a.length) > 0 ? "input-border" : ""} search-input`, ref: el => {
                this.searchInputElem = el;
                el === null || el === void 0 ? void 0 : el.focus();
            }, placeholder: this.searchResultSettings.placeholder, value: this.query, rows: 1, onInput: event => this.handleInput(event), onKeyDown: this.handleKeyDown, onKeyUp: this.adjustHeight, onFocus: () => {
                this.el.shadowRoot.querySelector("#searchPanel").classList.add("input-focus-color");
            }, onBlur: () => this.el.shadowRoot.querySelector("#searchPanel").classList.remove("input-focus-color") }), h("div", { key: '47b59abf36d6bd25e63277cb879b14b77139f072', role: "status", "aria-live": "polite", "aria-atomic": "true", class: "sr-only" }, this.announceMessage), h("span", { key: 'e8e923eb721aff3f32c0edc8946c63f3f637be44', class: "sr-only" }, "Press Enter to send, Shift+Enter for new line"))), h("div", { key: '4e991673952e48d449a492026c25fe2cb0e6af89', class: `icons flex items-center space-x-2 ${this.hideAllButtons ? "w-full" : "w-auto"}` }, this.searchResultSettings.enableMic && (h("span", { key: '37e6110b974ad66b1b919545a10b5655026691bd', class: "w-full mic-icon" }, h("audio-recorder", { key: 'd047c395b1aa0aaf9540cebe747df802ff910496', "component-type": "search", onStartRecord: _ev => {
                // console.log("test", ev)
                this.hideAllButtons = true;
            }, onStopRecord: _ev => {
                this.hideAllButtons = false;
            }, onSendTranscript: ev => {
                // console.log("ev", ev)
                setTimeout(() => {
                    // console.log("input", this.searchInputElem)
                    if (this.searchInputElem) {
                        this.searchInputElem.value = ev.detail;
                        this.query = ev.detail;
                        this.componentDidLoad();
                        // this.fetchSearchResults()
                        requestAnimationFrame(() => {
                            this.adjustHeight();
                        });
                    }
                }, 500);
            }, style: { width: "100%" } }))), !this.hideAllButtons && (h("span", { key: 'c70ecc73061059419b7580b3a8ec016aae79a78f', class: "search-icon" }, h("button", { key: 'b0098a988c6f647a5d18bb908333789203b8d175', id: "send-message-button", class: "text-white transition rounded-lg p-1.5 self-center submit-button chat-btn-primary", onClick: event => this.handleFormSubmit(event), "aria-label": "Send Message", tabindex: "0", title: "Send Message" }, h("svg", { key: 'f5f5384a893c6428da5191cd7027d69b74e1c8e6', xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 16 16", fill: "currentColor", class: "size-6" }, h("path", { key: 'e200594cb3c4f58dad9016ef9968d5279c5b1cd8', "fill-rule": "evenodd", d: "M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z", "clip-rule": "evenodd" })))))))), this.chatHistory.length === 0 && (h("div", { key: 'a30ec62df38c0948ee2a26c64d8a3524af178d87', class: `enter-tip ${this.searchResultSettings.textareaAtBottom ? "order-2 mt-1" : "order-1 mb-1"}`, role: "tooltip" }, "Tip: Press Enter to send, Shift+Enter for new line"))), this.emptyMessageError && (h("div", { key: '87a60945124ce40e9335491a4c4edef1a9a650ff', class: `error-message-container ${this.searchResultSettings.textareaAtBottom ? "order-2 mt-1" : "order-1 mb-1"}` }, h("span", { key: 'c5c7c695e17258c14c0498bd10a6f83b7fc02465', id: "search-message-error", class: "error-msg", role: "alert" }, "Message cannot be empty. Please enter a message to send."))), h("div", { key: 'bc7b965e227d33c62191e2447b5af7e6ed62dbfc', class: `chat-content-wrapper flex-1 overflow-y-auto ${this.searchResultSettings.textareaAtBottom ? "order-1" : "order-2"}` }, this.isChat && (h("ai12z-chat", { key: '80d16cf07a767b3f5a8c86b64b2b05ae96ca721e',
            // socket={this.socket}
            chats: this.chatHistory, env: this.dataMode, query: this.query, apiKey: this.dataKey, aiMessageId: this.aiMessageId, imgFiles: this.imgFiles, target: (_b = this.searchResultSettings.linkTarget) !== null && _b !== void 0 ? _b : "_blank", voiceType: (_c = this.searchResultSettings.voiceType) !== null && _c !== void 0 ? _c : "default", voice: (_d = this.searchResultSettings.voice) !== null && _d !== void 0 ? _d : "Google US English", onFeedback: async (event) => {
                const { feedback, insightId } = event.detail;
                sendFeedback(this.dataKey, this.dataMode, insightId, feedback);
            }, componentType: "search", dataAttributes: this.dataAttributes, socketIn: this.socketService, customJS: this.searchResultSettings.customJS, customstyle: this.searchResultSettings.customCSS, avatarUrl: this.searchResultSettings.botAvatar, settings: this.searchResultSettings })), this.showWelcomeTemplate && (h("div", { key: 'a9aad72d15e023cac75f7f77ddd8ff8e81a7d1b5', class: "welcome-template-container" }, h("div", { key: '3bd9befa93c4ba615dd3e89a38641dba9e1e7ba1', class: "welcome-template-content", innerHTML: (_e = this.searchResultSettings.welcome) === null || _e === void 0 ? void 0 : _e.message })))))), h("aside", { key: '567a46237b8ed757f33b15d4d7a2006e6d7c9e66', class: "quick-links-column", "aria-hidden": "true" }, this.searchResults && this.searchResults.length > 0 && (h("div", { key: '3fa34acaca471cf06dda61d4e3a870b8299051fb', class: { "search-results": this.searchResults && this.searchResults.length > 0 } }, h("h3", { key: '6998de65d81f0c269ead38ee34a69d7768a9e4cb', class: "title" }, "Sources"), this.searchResultSettings.categorize && (h("ai12z-category", { key: '9ca877f3362fd0db8da5b360341c4e7899181ea3', categoryList: this.searchResults, linkTarget: (_f = this.searchResultSettings.linkTarget) !== null && _f !== void 0 ? _f : "_blank" })), !this.searchResultSettings.categorize && h(SearchResult, { key: 'a8548ea4ede2244c879ffc747f4a88b39d98c352', results: this.searchResults, linkTarget: (_g = this.searchResultSettings.linkTarget) !== null && _g !== void 0 ? _g : "_blank" }))), !this.searchResults ||
            (this.searchResults.length === 0 && this.searchResultSettings.autoSearch && (h("div", { key: 'd5f54b0cd00daef3b9fca12f4ac55c90108555c0', class: "sources-panel" }, h("h3", { key: '12ee2ef054e81ff80e4b51e1c0e2df587aba656b', class: "title" }, "Sources"), h("div", { key: 'a2064c532a8c45ab7a276b29ecb649f8d78b350a', class: "skeleton-list" }, h("div", { key: '48f94b3d8a4e32ffd2a4d8fd04fc35ab57f0a916', class: "skeleton-line" }), h("div", { key: 'd4ae628639798ed7042cf566057407bd97a48cb5', class: "skeleton-line" }), h("div", { key: 'afffcb3536f319ddf4a369711af06f85bd9dd845', class: "skeleton-line short" }), h("div", { key: '570a7c60ca36469f71f8c8d56608a0675d744244', class: "divider" }), h("div", { key: '7df10951ab4415c7628a4feaccff5db49b46c310', class: "skeleton-line" }), h("div", { key: '93eff788b5d535702b013cd7597114cfb3e15dcd', class: "skeleton-line short" }), h("div", { key: '0216208144bf09c7bc430c76d63493f26ec263fd', class: "divider" }), h("div", { key: '29a4a1d59b8905bf78abe21307ee569dc1f30af1', class: "skeleton-line" }), h("div", { key: 'd3dff4636e37107fac5eb3262ddd5f07846cf7aa', class: "skeleton-line" }), h("div", { key: 'e4b133beb7466a5651deb63c656acb4c387bde2a', class: "skeleton-line short" }))))))))));
    }
    static get is() { return "search-results-page"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["search-results-view.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["search-results-view.css"]
        };
    }
    static get properties() {
        return {
            "dataKey": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "data-key",
                "defaultValue": "Env.DATA_KEY || \"\""
            },
            "dataMode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "data-mode",
                "defaultValue": "Env.DATA_MODE || \"prod\""
            },
            "dataAttributes": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "data-attributes"
            },
            "configId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "config-id"
            }
        };
    }
    static get states() {
        return {
            "query": {},
            "searchResultSettings": {},
            "searchResults": {},
            "hideAllButtons": {},
            "isChat": {},
            "chatHistory": {},
            "aiMessageId": {},
            "socketService": {},
            "thumbsId": {},
            "isOpen": {},
            "capturedFile": {},
            "imgFiles": {},
            "displayText": {},
            "showWelcomeTemplate": {},
            "timer": {},
            "questionCounter": {},
            "emptyMessageError": {},
            "announceMessage": {},
            "isRendered": {}
        };
    }
    static get events() {
        return [{
                "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": "errored",
                "name": "errored",
                "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": "any",
                    "resolved": "any",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "sendMessage": {
                "complexType": {
                    "signature": "(message: string, displayText?: string) => Promise<void>",
                    "parameters": [{
                            "name": "message",
                            "type": "string",
                            "docs": ""
                        }, {
                            "name": "displayText",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "sendJSON": {
                "complexType": {
                    "signature": "(jsonData: 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": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get listeners() {
        return [{
                "name": "messageReceived",
                "method": "messageReceivedHandler",
                "target": "document",
                "capture": false,
                "passive": false
            }, {
                "name": "survey",
                "method": "surveyHandler",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
