import { h } from "@stencil/core";
import { initializeScript as initializeScriptHelper } from "../../../utils/botHelpers/botHelpers";
import { adoptStyleSheet, loadScriptOnce } from "../../../utils/styleSheetRegistry";
export class Ai12zChatMessage {
    constructor() {
        this.text = ""; // incoming markdown/html
        this.streaming = false;
        this.showButton = true;
        this.isExpanded = false;
        this.isCollapsing = false;
        this.canExpand = false;
        this.surveyCDNPath = "https://cdn.ai12z.net/pkg/surveyjs";
        /* ---------- Toggle expand/collapse ---------- */
        this.toggleExpand = () => {
            if (this.isExpanded) {
                // COLLAPSING
                this.isCollapsing = true;
                // Step 1: animate height down
                const collapsedHeight = this.getCollapsedHeight();
                this.messageRef.style.maxHeight = `${collapsedHeight}px`;
                // Step 2: after animation, apply clamp
                setTimeout(() => {
                    this.isExpanded = false;
                    this.isCollapsing = false;
                }, 300); // must match CSS transition
            }
            else {
                // EXPANDING
                this.isExpanded = true;
                const collapsedHeight = this.getCollapsedHeight();
                this.messageRef.style.maxHeight = `${collapsedHeight}px`;
                // Force reflow
                this.messageRef.offsetHeight;
                requestAnimationFrame(() => {
                    const fullHeight = this.messageRef.scrollHeight;
                    this.messageRef.style.maxHeight = `${fullHeight}px`;
                });
            }
        };
    }
    get mainObject() {
        if (!window["ai12z"]) {
            window["ai12z"] = {};
        }
        return window["ai12z"];
    }
    handleInitializeScripts(event) {
        initializeScriptHelper(event.detail.id, this.mainObject);
    }
    componentWillLoad() {
        var _a, _b;
        this.loadScriptsSequentially();
        // Adopt customCSS in this shadow root using the shared CSSStyleSheet
        // already constructed by the parent knowledge-box (zero extra fetches).
        if ((_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.customCSS) {
            adoptStyleSheet(this.kbSettings.customCSS, this.el.shadowRoot);
        }
        if ((_b = this.kbSettings) === null || _b === void 0 ? void 0 : _b.customJS) {
            loadScriptOnce(this.kbSettings.customJS, this.el.shadowRoot);
        }
    }
    componentDidLoad() {
        // Initialise the ai12z global exactly once; never overwrite an existing value.
        if (!window["ai12z"]) {
            window["ai12z"] = {};
        }
        const ai12zHeading = document.createElement("script");
        ai12zHeading.text = `var ai12zChat = window["ai12z"] = {}`;
        this.el.shadowRoot.appendChild(ai12zHeading);
        this.checkOverflow();
    }
    async loadScriptsSequentially() {
        try {
            // Survey.js scripts are loaded into shadowRoot exactly once
            // (loadScriptOnce deduplicates across all component instances).
            await loadScriptOnce(`${this.surveyCDNPath}/survey-core@2.3.4/survey.core.min.js`, this.el.shadowRoot);
            await loadScriptOnce(`${this.surveyCDNPath}/survey-core@2.3.4/survey.i18n.min.js`, this.el.shadowRoot);
            await loadScriptOnce(`${this.surveyCDNPath}/survey-core@2.3.4/themes/index.min.js`, this.el.shadowRoot);
            await loadScriptOnce(`${this.surveyCDNPath}/survey-js-ui@2.3.4/survey-js-ui.min.js`, this.el.shadowRoot);
        }
        catch (error) {
            console.error("Failed to load Survey.js scripts:", error);
        }
    }
    onTextChange() {
        // if (!this.isExpanded && !this.streaming) {
        //   this.updateCollapsedHeight();
        // }
        // if (this.isExpanded) {
        //   this.updateExpandedHeight();
        // }
        this.checkOverflow();
    }
    updateCollapsedHeight() {
        requestAnimationFrame(() => {
            const height = this.getCollapsedHeight();
            this.messageRef.style.maxHeight = `${height}px`;
        });
    }
    updateExpandedHeight() {
        requestAnimationFrame(() => {
            this.messageRef.style.maxHeight = `${this.messageRef.scrollHeight}px`;
        });
    }
    getCollapsedHeight() {
        if (!this.messageRef)
            return 0;
        // Apply clamp temporarily
        this.messageRef.classList.add("custom-line-clamp");
        // Force layout
        const height = this.messageRef.getBoundingClientRect().height;
        // Clean up if expanded
        if (this.isExpanded) {
            this.messageRef.classList.remove("custom-line-clamp");
        }
        return height;
    }
    checkOverflow() {
        var _a, _b;
        if (!this.messageRef)
            return;
        const lineClamp = (_b = (_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.numberOfLines) !== null && _b !== void 0 ? _b : 10;
        // If numberOfLines is 0, show everything without clamping
        if (lineClamp === 0) {
            this.canExpand = false;
            this.messageRef.classList.remove("custom-line-clamp");
            this.messageRef.style.maxHeight = "none";
            return;
        }
        requestAnimationFrame(() => {
            // Measure full height
            this.messageRef.classList.remove("custom-line-clamp");
            const fullHeight = this.messageRef.scrollHeight;
            // Measure clamped height
            this.messageRef.classList.add("custom-line-clamp");
            const clampedHeight = this.messageRef.getBoundingClientRect().height;
            this.canExpand = fullHeight > clampedHeight + 1;
            if (!this.showButton) {
                this.canExpand = false;
            }
            // Cleanup if no overflow
            if (!this.canExpand) {
                this.messageRef.classList.remove("custom-line-clamp");
                this.messageRef.style.maxHeight = "none";
            }
        });
    }
    /* ---------- Render ---------- */
    render() {
        var _a, _b, _c, _d;
        const lineClamp = (_b = (_a = this.kbSettings) === null || _a === void 0 ? void 0 : _a.numberOfLines) !== null && _b !== void 0 ? _b : 10;
        return (h("div", { key: '54f51ffb7c06bbb20fc1088c0fb63a8669d7ba45', class: "chat-message" }, h("div", { key: '281bc75361bcfadb4611eefeb9697d525b9e2d27', ref: (el) => this.messageRef = el, class: { 'message-text': true, "custom-line-clamp": !this.isExpanded && !this.isCollapsing && this.showButton }, style: {
                "--line-clamp": `${lineClamp}`,
            }, innerHTML: this.text, onClick: this.showButton ? this.toggleExpand : undefined }), !this.isExpanded && this.showButton && this.canExpand && h("div", { key: 'd6e262dbca0934b97fafb3dd7723b3b9333d8e10', class: "fade-overlay" }), this.showButton && this.canExpand && h("button", { key: 'e1e711b71656763ecdeb1cb6f73166528f023914', class: "show-more-btn", onClick: this.toggleExpand }, this.isExpanded ? (((_c = this.kbSettings) === null || _c === void 0 ? void 0 : _c.showLessButtonLabel) || "Show less") : (((_d = this.kbSettings) === null || _d === void 0 ? void 0 : _d.showMoreButtonLabel) || "Show more"), this.isExpanded ? h("svg", { width: "1em", height: "1em", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }, h("polyline", { points: "6 9 12 15 18 9" })) : h("svg", { width: "1em", height: "1em", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }, h("polyline", { points: "18 15 12 9 6 15" })))));
    }
    static get is() { return "ai12z-chat-message"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["ai12z-chat-message.css", "../../../global/survey-core.min.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ai12z-chat-message.css", "../../../global/survey-core.min.css"]
        };
    }
    static get properties() {
        return {
            "text": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "text",
                "defaultValue": "\"\""
            },
            "streaming": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "streaming",
                "defaultValue": "false"
            },
            "kbSettings": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "kb-settings"
            },
            "showButton": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-button",
                "defaultValue": "true"
            }
        };
    }
    static get states() {
        return {
            "isExpanded": {},
            "isCollapsing": {},
            "canExpand": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "text",
                "methodName": "onTextChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "initializeScripts",
                "method": "handleInitializeScripts",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
