import { h } from "@stencil/core";
import { Logger, LogLevel } from "../../../../utils/logger";
const logger = new Logger("LiveAgentChat", {
    logLevel: LogLevel.Info, // Set to Debug for detailed logs",
    remoteLoggingUrl: "",
});
export class LiveAgentChat {
    constructor() {
        /**
         * Internal state to track if the LiveAgent API is ready.
         */
        this.isApiReady = false;
        this.chatButton = null;
        this.buttonId = "ucu6zapn";
    }
    /**
     * Stencil lifecycle hook that runs once when the component is first connected to the DOM.
     */
    componentWillLoad() {
        var _a;
        if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.buttonId) || !this.config.scriptSrc) {
            logger.error("LiveAgentChat: `buttonId` and `scriptSrc` properties are required.");
            return;
        }
        this.loadLiveAgentScript();
    }
    /**
     * Dynamically loads the LiveAgent track.js script into the document.
     */
    loadLiveAgentScript() {
        var _a;
        // Check if the script is already added to avoid duplicates
        if (document.getElementById("la_x2s6df8d")) {
            this.initializeApi();
            return;
        }
        const script = document.createElement("script");
        script.id = "la_x2s6df8d";
        script.async = true;
        script.src = (_a = this.config) === null || _a === void 0 ? void 0 : _a.scriptSrc;
        script.onload = () => {
            if (window.LiveAgent) {
                this.chatButton = window.LiveAgent.createVirtualButton(this.buttonId, script);
                this.initializeApi();
            }
        };
        document.body.appendChild(script);
    }
    /**
     * Initializes the event handlers for the LiveAgent API, waiting for it to be ready.
     */
    initializeApi() {
        if (window === null || window === void 0 ? void 0 : window.LiveAgent) {
            this.isApiReady = true;
        }
        else {
            logger.error("LiveAgentChat: LiveAgent API is not available or `whenReady` is not a function.");
        }
    }
    // 🔹 Public method to start the chat manually
    async startChat(_buttonId) {
        var _a, _b, _c, _d;
        if (!this.isApiReady) {
            logger.error("LiveAgentChat: API is not ready. Cannot start chat.");
            return Promise.reject("API not ready");
        }
        (_a = this.chatButton) === null || _a === void 0 ? void 0 : _a.onClick();
        (_c = (_b = window.LiveAgent) === null || _b === void 0 ? void 0 : _b.startChat) === null || _c === void 0 ? void 0 : _c.call(_b, _buttonId || ((_d = this.config) === null || _d === void 0 ? void 0 : _d.buttonId));
        window.addEventListener("message", event => {
            var _a, _b;
            if (event.origin.includes("ladesk.com")) {
                if ((_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.includes("onEmbeddedChatOpened")) {
                    try {
                        const botElement = document.querySelector("ai12z-bot");
                        botElement.action("minimize");
                    }
                    catch (error) {
                        logger.error("Error fetching data:", error);
                    }
                }
                if ((_b = event === null || event === void 0 ? void 0 : event.data) === null || _b === void 0 ? void 0 : _b.includes("closeOpenedWidget")) {
                    try {
                        const botElement = document.querySelector("ai12z-bot");
                        botElement.action("open", { expanded: false });
                    }
                    catch (error) {
                        logger.error("Error fetching data:", error);
                    }
                }
            }
        });
        return Promise.resolve();
    }
    /**
     * This component does not render its own UI. It provides functionality
     * to its parent through events and methods. A <slot> can allow the parent
     * to project content if needed, but is not required.
     */
    render() {
        return h("slot", { key: 'a0d32db2683a293d3b4b232fc65cd63461670af1' });
    }
    static get is() { return "live-agent-chat"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "config": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "config"
            }
        };
    }
    static get states() {
        return {
            "isApiReady": {}
        };
    }
    static get methods() {
        return {
            "startChat": {
                "complexType": {
                    "signature": "(_buttonId?: string) => Promise<void>",
                    "parameters": [{
                            "name": "_buttonId",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
}
