import { r as registerInstance, a as createEvent, h, d as getElement } from './index-BNpVu1WU.js';

const chatHistoryCss = () => `:host{font-family:var(--ai12zBot-v2-font-family) !important;font-size:var(--ai12zBot-v2-font-size) !important}.history-list{margin:0;padding:0;list-style:none}.conversation-list-item{border-bottom:1px solid #dcdcdc;padding:0;transition:background 0.4s ease;cursor:pointer}.conversation-list-item-body{display:flex;align-items:center;display:flex;margin:8px 16px}.conversation-list-item-body-content{margin:0 0 0 16px;position:relative;width:calc(100% - 48px)}.conversation-list-item-body-content h2{font-size:14px;margin:0}.conversation-list-item-time{color:var(--ai12z-bot-history-text-color);font-size:12px;position:absolute;right:0;top:2px}.conversation-list-item-last-message{margin:0;padding:0;max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:var(--ai12z-bot-history-text-color);font-size:14px}.avatar{width:30px;height:30px;border-radius:50%;margin-right:10px}.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}.conversation-list-item{outline:none;}.conversation-list-item:focus-visible{outline:3px solid var(--ai12zBot-v2-focus-visible-color-primary, #2563eb);outline-offset:2px;border-radius:6px}.conversation-list-item.active{background:#f3f4f6;border-left:3px solid var(--ai12zBot-v2-primary-color)}`;

const ChatbotHistory = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.chatClick = createEvent(this, "chatClick", 7);
        this.deleteChatHistory = createEvent(this, "deleteChatHistory", 7);
        this.cdnPath = "https://cdn.ai12z.net/assets/bot";
        this.chatList = [];
        this.botName = "AI12z Bot";
        this.chatlogo = this.cdnPath + `/v1/ai12z-bot/img/chatbot.jpg`;
        this.heading = "Chat history";
        this.styles = "";
        this.scripts = "";
        this.showDeleteModal = false;
        this.chatToDelete = null;
        this.activeId = null;
        this.focusedIndex = -1;
        this.chatHistoryRefs = [];
    }
    handleClick(chat) {
        this.chatClick.emit(JSON.parse(JSON.stringify(chat)));
    }
    componentWillLoad() {
        var _a, _b;
        if (this.styles) {
            this.insertStyles(this.styles);
        }
        if (this.scripts) {
            const scriptEl = document.createElement("script");
            scriptEl.setAttribute("src", this.scripts);
            scriptEl.setAttribute("type", "text/javascript");
            scriptEl.setAttribute("async", "true");
            const shadowRoot = this.element.shadowRoot;
            if (shadowRoot) {
                shadowRoot.appendChild(scriptEl);
            }
        }
        if (!this.activeId && ((_a = this.chatList) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            this.activeId = this.chatList[((_b = this.chatList) === null || _b === void 0 ? void 0 : _b.length) - 1].conversationId;
            this.focusedIndex = 0;
        }
    }
    componentDidLoad() {
        var _a;
        // Set initial focus to first item if available
        if (((_a = this.chatList) === null || _a === void 0 ? void 0 : _a.length) > 0 && this.chatHistoryRefs[0]) {
            setTimeout(() => {
                var _a;
                (_a = this.chatHistoryRefs[0]) === null || _a === void 0 ? void 0 : _a.focus();
            }, 100);
        }
    }
    insertStyles(linkURL) {
        const linkEl = document.createElement("link");
        linkEl.setAttribute("rel", "stylesheet");
        linkEl.setAttribute("href", linkURL);
        const shadowRoot = this.element.shadowRoot;
        if (shadowRoot) {
            shadowRoot.appendChild(linkEl);
        }
    }
    deleteHistory(chat) {
        this.deleteChatHistory.emit(chat);
    }
    convertHtmlToPlainText(html) {
        var temp = document.createElement("div");
        temp.innerHTML = html;
        return temp.textContent || temp.innerText || "";
    }
    sortByDateDesc() {
        return this.chatList.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    }
    filterMessages(chat) {
        if (!(chat === null || chat === void 0 ? void 0 : chat.messages)) {
            return []; // Return empty array if no messages
        }
        return chat.messages.reduce((acc, message) => {
            var _a, _b;
            if (message.isUser === true || message.type === "user") {
                acc.push({ user: (_a = message.text) !== null && _a !== void 0 ? _a : message.message });
            }
            else if (message.isUser === false || message.type === "ai") {
                acc.push({ agent: this.parseHtmlToText((_b = message.text) !== null && _b !== void 0 ? _b : message.message) });
            }
            return acc;
        }, []);
    }
    parseHtmlToText(html) {
        const parser = new DOMParser();
        // Parse the HTML string into a document
        const doc = parser.parseFromString(html, "text/html");
        // Get the text content from the document, stripping out the HTML tags
        return doc.body.textContent || "";
    }
    downloadChat(chat, event) {
        event === null || event === void 0 ? void 0 : event.stopPropagation();
        // console.log("*********", chat)
        const filteredMessages = this.filterMessages(chat);
        let transcriptText = new Date(chat.date).toLocaleString() + "\n"; // Add a new line at the top
        // Create the text version of the chat
        transcriptText += filteredMessages
            .map(message => {
            if (message.user) {
                return `You: ${message.user}`;
            }
            else if (message.agent) {
                return `Agent: ${message.agent}`;
            }
        })
            .join("\n"); // Join with a new line
        // Create a Blob for the text file
        const blob = new Blob([transcriptText], { type: "text/plain" });
        // Convert chat history to JSON string
        // const dataStr = JSON.stringify(filteredMessages, null, 2)
        // Create a Blob object
        // const blob = new Blob([dataStr], { type: "application/json" })
        // Create a link element
        const downloadLink = document.createElement("a");
        downloadLink.href = URL.createObjectURL(blob);
        downloadLink.download = `chat-${new Date(chat.date).getTime()}.txt`; // Name of the file
        // Programmatically click the link to trigger download
        downloadLink.click();
    }
    // Open the confirmation dialog
    confirmDelete(chat, event) {
        if (event) {
            event.stopPropagation();
            event.preventDefault();
        }
        this.activeId = chat.conversationId;
        this.chatToDelete = chat;
        this.showDeleteModal = true;
    }
    // Delete the chat
    handleConfirmDelete() {
        if (this.chatToDelete) {
            this.deleteChatHistory.emit(this.chatToDelete);
        }
        this.chatToDelete = null;
        this.showDeleteModal = false;
    }
    // Cancel deletion
    handleCancelDelete() {
        this.chatToDelete = null;
        this.showDeleteModal = false;
    }
    handleMessageKeyNav(e, idx) {
        var _a, _b;
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            e.stopPropagation();
            const nextIndex = Math.min(this.chatList.length - 1, idx + 1);
            this.focusedIndex = nextIndex;
            this.activeId = this.chatList[nextIndex].conversationId;
            (_a = this.chatHistoryRefs[nextIndex]) === null || _a === void 0 ? void 0 : _a.focus();
        }
        else if (e.key === 'ArrowUp') {
            e.preventDefault();
            e.stopPropagation();
            const prevIndex = Math.max(0, idx - 1);
            this.focusedIndex = prevIndex;
            this.activeId = this.chatList[prevIndex].conversationId;
            (_b = this.chatHistoryRefs[prevIndex]) === null || _b === void 0 ? void 0 : _b.focus();
        }
    }
    render() {
        const sortedItems = this.sortByDateDesc();
        return (h("div", { key: '6595986513b8c8ac3daf7c8b92306cc27e3f7585', role: "list", "aria-label": "Chat history" }, h("ul", { key: '701836339305fb6af977a02c9eb95a201cb47977', class: "history-list" }, sortedItems.length === 0 && h("p", { key: '68756ec13d02e46b490a85fa1e176a6cd98c777e', class: "no-history" }, "No chat history available"), sortedItems.map((chat, idx) => {
            var _a;
            return (h("li", { class: `conversation-list-item ${chat.conversationId === this.activeId ? 'active' : ''}`, onClick: () => this.handleClick(chat.messages), role: "listitem", "aria-label": `Chat from ${new Date(chat.date).toLocaleString()}`, "aria-selected": chat.conversationId === this.activeId, tabindex: idx === this.focusedIndex ? 0 : -1, onKeyDown: (e) => this.handleMessageKeyNav(e, idx), ref: el => (this.chatHistoryRefs[idx] = el) }, h("div", { class: `conversation-list-item-body` }, h("div", null, h("img", { class: "avatar", src: this.chatlogo, alt: "Avatar" })), h("div", { class: "conversation-list-item-body-content" }, h("h2", null, new Date(chat.date).toLocaleString()), h("span", { class: "conversation-list-item-time" }, h("button", { onClick: (event) => this.downloadChat(chat, event), "aria-label": "Download chat", style: { background: "none", border: "none", padding: "0", cursor: "pointer", marginRight: "10px" } }, h("svg", { viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", height: "20px", width: "20px",
                // onClick={() => this.downloadChat(chat)}
                style: { "margin-right": "10px" } }, h("path", { opacity: "0.5", d: "M3 15C3 17.8284 3 19.2426 3.87868 20.1213C4.75736 21 6.17157 21 9 21H15C17.8284 21 19.2426 21 20.1213 20.1213C21 19.2426 21 17.8284 21 15", stroke: "#1C274C", "stroke-width": "1.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), " ", h("path", { d: "M12 3V16M12 16L16 11.625M12 16L8 11.625", stroke: "#1C274C", "stroke-width": "1.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), " ")), h("button", { onClick: (event) => this.confirmDelete(chat, event), "aria-label": "Delete chat", "aria-describedby": `delete-warning-${chat.id}`, style: { background: "none", border: "none", padding: "0", cursor: "pointer" } }, h("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 29 29", id: "delete", height: "20px", width: "20px" }, h("path", { d: "M10 3v3h9V3a1 1 0 0 0-1-1h-7a1 1 0 0 0-1 1z" }), h("path", { d: "M4 5v1h21V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1zM6 8l1.812 17.209A2 2 0 0 0 9.801 27H19.2a2 2 0 0 0 1.989-1.791L23 8H6zm4.577 16.997a.999.999 0 0 1-1.074-.92l-1-13a1 1 0 0 1 .92-1.074.989.989 0 0 1 1.074.92l1 13a1 1 0 0 1-.92 1.074zM15.5 24a1 1 0 0 1-2 0V11a1 1 0 0 1 2 0v13zm3.997.077a.999.999 0 1 1-1.994-.154l1-13a.985.985 0 0 1 1.074-.92 1 1 0 0 1 .92 1.074l-1 13z" }))), h("span", { id: `delete-warning-${chat.id}`, class: "sr-only" }, "This action cannot be undone"), this.showDeleteModal && this.chatToDelete === chat && (h("delete-confirmation-modal", { show: true, onConfirmDelete: () => this.handleConfirmDelete(), onCancelDelete: () => this.handleCancelDelete() }))), h("p", { class: "conversation-list-item-last-message" }, " ", this.convertHtmlToPlainText((_a = chat.messages[0].text) !== null && _a !== void 0 ? _a : chat.messages[0].message), " ")))));
        }))));
    }
    get element() { return getElement(this); }
};
ChatbotHistory.style = chatHistoryCss();

const deleteConfirmationModalCss = () => `:host{font-family:var(--ai12z-bot-font-family, ui-sans-serif, system-ui, sans-serif)}.modal-backdrop{position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0, 0, 0, 0.5);display:flex;justify-content:center;align-items:center;isolation:isolate;z-index:20000}.modal-content{background:white;padding:24px;border-radius:8px;box-shadow:0 4px 6px rgba(0, 0, 0, 0.1);max-width:400px;width:90%;outline:none}.modal-content h2{margin:0 0 12px 0;font-size:18px;font-weight:600;color:#333}.modal-content p{margin:0 0 20px 0;font-size:14px;color:#595959;line-height:1.5}.modal-buttons{display:flex;justify-content:flex-end;gap:12px}.modal-buttons button{padding:8px 16px;border:none;border-radius:4px;font-size:14px;font-weight:500;cursor:pointer;transition:background-color 0.2s ease}.delete-button{background-color:var(--ai12zBot-v2-primary-color, var(--ai12z-primary-color));color:white}.delete-button:hover{background-color:var(--ai12zBot-v2-primary-color, var(--ai12z-primary-color))}.delete-button:focus{outline:2px solid var(--ai12zBot-v2-primary-color, var(--ai12z-primary-color));outline-offset:2px}.cancel-button{background-color:#e5e7eb;color:#374151}.cancel-button:hover{background-color:#d1d5db}.cancel-button:focus{outline:2px solid #9ca3af;outline-offset:2px}`;

const DeleteConfirmationModal = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.confirmDelete = createEvent(this, "confirmDelete", 7);
        this.cancelDelete = createEvent(this, "cancelDelete", 7);
        this.show = false;
        this.dialogTitle = "Confirm Delete";
        this.message = "Are you sure you want to delete this chat? This action cannot be undone.";
        this.confirmButtonText = "Delete";
        this.cancelButtonText = "Cancel";
    }
    handleConfirm() {
        this.confirmDelete.emit();
    }
    handleCancel() {
        this.cancelDelete.emit();
    }
    handleKeyDown(event) {
        if (event.key === "Escape") {
            event.preventDefault();
            this.handleCancel();
        }
    }
    render() {
        if (!this.show) {
            return null;
        }
        return (h("div", { role: "dialog", "aria-modal": "true", "aria-labelledby": "delete-dialog-title", "aria-describedby": "delete-dialog-desc", class: "modal-backdrop", onClick: () => this.handleCancel(), onKeyDown: event => this.handleKeyDown(event) }, h("div", { class: "modal-content", role: "document", tabIndex: -1, onClick: (e) => e.stopPropagation() }, h("h2", { id: "delete-dialog-title" }, this.dialogTitle), h("p", { id: "delete-dialog-desc" }, this.message), h("div", { class: "modal-buttons" }, h("button", { onClick: () => this.handleConfirm(), autoFocus: true, class: "delete-button" }, this.confirmButtonText), h("button", { onClick: () => this.handleCancel(), class: "cancel-button" }, this.cancelButtonText)))));
    }
};
DeleteConfirmationModal.style = deleteConfirmationModalCss();

export { ChatbotHistory as chatbot_history, DeleteConfirmationModal as delete_confirmation_modal };
