'use strict';

var index = require('./index-Ct2DwlDF.js');
var utils = require('./utils-BAJarpnb.js');
var SearchResult = require('./SearchResult-DirxAsMi.js');
var socketService = require('./socket-service-L0xv4YGT.js');
require('./response-adapter-CKKyyhMj.js');

const ai12zInlineSearchCss = () => `:host{font-family:var(--ai12z-font-family) !important;font-size:var(--ai12z-font-size) !important;color:var(--ai12z-font-color, black);text-align:var(--ai12z-text-align, left)}`;

const Ai12zInlineSearch = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.stateChanged = index.createEvent(this, "stateChanged", 7);
        this.startStream = index.createEvent(this, "startStream", 7);
        this.streamResponse = index.createEvent(this, "streamResponse", 7);
        this.startInlineResponse = index.createEvent(this, "startInlineResponse", 7);
        this.endResponse = index.createEvent(this, "endResponse", 7);
        this.dataKey = index.Env.DATA_KEY || "";
        this.dataMode = index.Env.DATA_MODE || "prod";
        this.resultPosition = "below";
        this.autoSearch = true;
        this.categorize = true;
        this.settings = {};
        this.formData = { search: "" };
        this.conversationHistory = [];
        this.searchResults = [];
        this.isOpen = false; // State to manage modal visibility
        this.aiMessageId = "";
        this.ctaSettings = {};
        this.imgFiles = [];
        this.thumbsId = "";
        this.isChat = false;
        this.isSubmitted = false;
        this.handleSubmit = async (event, value, type, followUp, imgFiles) => {
            var _a;
            event.preventDefault();
            this.isOpen = true;
            // this.formData = { ...this.formData, [type]: value }
            this.formData = Object.assign(Object.assign({}, this.formData), { search: value });
            this.imgFiles = imgFiles;
            if (!followUp && type === "follow-up") {
                this.conversationHistory = [];
                this.isChat = false;
            }
            if (!this.formData.search && ((_a = this.formData.search) === null || _a === void 0 ? void 0 : _a.trim().length) < 3 && imgFiles && imgFiles.length < 1) {
                this.isSubmitted = false;
                this.stateChanged.emit(false);
                return;
            }
            try {
                let response = { answer: "", formModel: null, insight_id: null };
                if (type === "ask-ai" || this.isChat) {
                    this.isChat = true;
                    this.conversationHistory.push({
                        message: this.formData.search,
                        images: imgFiles,
                        status: "success",
                        type: "user",
                    });
                    this.aiMessageId = `ai-message-${utils.generateUUID()}`;
                    this.thumbsId = utils.generateUUID();
                    this.conversationHistory.push({
                        message: `<div class="animate-ping">...</div>`,
                        type: "ai",
                        status: "pending",
                        id: this.aiMessageId,
                    });
                    if (imgFiles && imgFiles.length > 0) {
                        this.imgFiles = imgFiles;
                    }
                    this.conversationHistory.pop();
                    response.answer = response === null || response === void 0 ? void 0 : response.answer;
                    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,
                    };
                    this.conversationHistory = [...this.conversationHistory, lastMessage];
                    this.startStream.emit({ search: this.formData.search });
                }
                else {
                    if (this.autoSearch) {
                        response = await utils.search(this.dataKey, this.dataMode, this.formData.search.trim());
                        this.displaySearchResults(response);
                    }
                }
            }
            catch (error) {
                console.error(error);
                // this.error = error
            }
            finally {
                this.isSubmitted = false;
                this.stateChanged.emit(false);
            }
        };
        this.displaySearchResults = results => {
            this.searchResults = results.docs || [...[]];
            this.isSubmitted = false;
        };
    }
    componentWillLoad() {
        utils.insertStyles(`https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css`, this.el);
        // this.socketService = SocketService.getInstance(this.dataMode)
        this.socketService = socketService.SocketService.createInstance(this.dataMode, this.dataKey);
        // console.log("socketService", this.socketService)
    }
    surveyHandler(_state) {
        if (_state.detail.type === "button") {
            this.handleSubmit(null, _state.detail.results, _state.detail.type, false, null);
        }
        else if (_state.detail.type === "carousel") {
            this.conversationHistory = [...this.conversationHistory, _state.detail.results];
        }
        else if (_state.detail.type === "update") {
            const idx = this.conversationHistory.findIndex(item => item.id === _state.detail.results.id);
            this.conversationHistory = [...this.conversationHistory.slice(0, idx), _state.detail.results, ...this.conversationHistory.slice(idx + 1)];
        }
    }
    render() {
        return (index.h("div", { key: '256811876b1812e2a553e01cadde90cafbbc6bae', style: { width: "100%" }, class: "container flex flex-col" }, this.resultPosition === "above" && (index.h("div", { key: '68df7633e92e250bb81346df394d2e7e99d0bf0f', class: "relative custom-results" }, !this.isChat && !this.categorize && this.isOpen && index.h(SearchResult.SearchResult, { key: 'c4ec5436420593c0cf1c34d25e812725ecae13c8', results: this.searchResults }), !this.isChat && this.categorize && this.isOpen && index.h("ai12z-category", { key: 'ee58ca678373419bc62fa25611a480b35a21c912', categoryList: this.searchResults, linkTarget: "_blank" }))), this.resultPosition === "above" && (index.h("div", { key: '0f44b283d78d4747ffafeee7ed5df62559c7011c' }, this.isChat && (index.h("ai12z-chat", { key: '26e8489fb9d621dd57a23f31c0d7d33464d8966f',
            // socket={this.socket}
            chats: this.conversationHistory, env: this.dataMode, query: this.formData.search, apiKey: this.dataKey, aiMessageId: this.aiMessageId, imgFiles: this.imgFiles, target: "_blank", voiceType: "default", voice: "Google US English", onFeedback: async (event) => {
                const { feedback, insightId } = event.detail;
                // console.log(feedback, insightId)
                utils.sendFeedback(this.dataKey, this.dataMode, insightId, feedback);
            }, componentType: "inline", chatPosition: this.resultPosition, socketIn: this.socketService, settings: this.settings })))), index.h("div", { key: '3bb2dfde5d351ce389fff4a803a93d585c8ceeb9', class: "search-bar" }, index.h("ai12z-input-form", { key: '69939209b18b7e32cba1f0b049037668bc47d417', onAction: async (event) => {
                const { value, type, followUp, imgFiles } = event.detail;
                // console.log(value, type, followUp, imgFiles)
                await this.handleSubmit(event, value, type, followUp, imgFiles);
            }, isChat: this.isChat, placeholder: "AI search", buttonText: "Ask AI", iconSrc: "", followUpLabel: "Do you have a follow up question?", isImageUpload: true, isEnableMic: true, componentType: "inline" })), this.resultPosition === "below" && (index.h("div", { key: '0af90bc1cd0052371cf406e15c79ce6150bbd90b', class: "relative custom-results" }, !this.isChat && !this.categorize && this.isOpen && index.h(SearchResult.SearchResult, { key: '50a78df450b7b8cc50a0584e0eb74422c374e00c', results: this.searchResults }), !this.isChat && this.categorize && this.isOpen && index.h("ai12z-category", { key: '9890780f2db4f2360d388a2942b596f4d89885e2', categoryList: this.searchResults, linkTarget: "_blank" }))), this.resultPosition === "below" && (index.h("div", { key: 'e77cd2f8f8a238934f8843c8f8321440956f0b25' }, this.isChat && (index.h("ai12z-chat", { key: '1744ceedb75c7b3eb4c8121ee1b07705c0f0ae7d',
            // socket={this.socket}
            chats: this.conversationHistory, env: this.dataMode, query: this.formData.search, apiKey: this.dataKey, aiMessageId: this.aiMessageId, imgFiles: this.imgFiles, target: "_blank", voiceType: "default", voice: "Google US English", onFeedback: async (event) => {
                const { feedback, insightId } = event.detail;
                // console.log(feedback, insightId)
                utils.sendFeedback(this.dataKey, this.dataMode, insightId, feedback);
            }, componentType: "inline", chatPosition: this.resultPosition, socketIn: this.socketService, settings: this.settings }))))));
    }
    get el() { return index.getElement(this); }
};
Ai12zInlineSearch.style = ai12zInlineSearchCss();

exports.ai12z_inline_search = Ai12zInlineSearch;
