<template>
    <div ref="sierraContainer"></div>
</template>

<script>
import analyticsMixin from "@/mixins/analytics-mixin";
export default {
    name: "sierraWebchat",
    mixins: [analyticsMixin],
    methods: {
        openSierraChatModal() {
            const sierra = window.sierraChat || window.sierra || window.SierraChat;
            if (sierra && typeof sierra.openChatModal === "function") {
                sierra.openChatModal();
            } else {
                const launchLink = document.createElement("a");
                launchLink.setAttribute("data-sierra-chat", "modal");
                launchLink.style.display = "none";
                document.body.appendChild(launchLink);
                launchLink.click();
                document.body.removeChild(launchLink);
            }
            this.pushEventForChatsToGA("support_chat", "chat_opened", "Scarlett", true);
        },
        createSierraConfig() {
            return {
                variables: { application: "funnel" },
                display: "corner",
                onLoad: () => this.openSierraChatModal(),
                onOpen: () => {},
                onClose: () => window.dispatchEvent(new CustomEvent("sierra-chat-closed")),
                onTransfer: (transfer) =>
                    window.dispatchEvent(
                        new CustomEvent("sierra-chat-transfer", { detail: transfer })
                    ),
            };
        },
        launchSierraChat() {
            window.sierraConfig = this.createSierraConfig();
            // Preload CSS if not already present
            if (!document.getElementById("sierra-chat-embed-css")) {
                const link = document.createElement("link");
                link.rel = "preload";
                link.as = "style";
                link.href =
                    "https://sierra.chat/agent/OxY5TbsBlJZsHxIBlJZsmCiQdcXfa2rePO38ZwOlx40/embed-css";
                link.id = "sierra-chat-embed-css";
                document.head.appendChild(link);
            }
            // Load script if not loaded, otherwise open modal directly
            if (!document.getElementById("sierra-chat-embed")) {
                const script = document.createElement("script");
                script.type = "module";
                script.id = "sierra-chat-embed";
                script.src =
                    "https://sierra.chat/agent/OxY5TbsBlJZsHxIBlJZsmCiQdcXfa2rePO38ZwOlx40/embed";
                document.body.appendChild(script);
            } else {
                this.openSierraChatModal();
            }
        },
        triggerSierraChat() {
            this.launchSierraChat();
        },
        closeSierraChat() {
            const sierra = window.sierraChat || window.sierra || window.SierraChat;
            if (sierra && typeof sierra.closeChatModal === "function") {
                sierra.closeChatModal();
            }
        },
    },
    mounted() {
        window.addEventListener("launch-sierra-webchat", this.triggerSierraChat);
        // Listen for transfer event to close Sierra chat and open Salesforce chat
        this._handleSierraTransfer = (event) => {
            const sierra = window.sierraChat || window.sierra || window.SierraChat;
            if (sierra && typeof sierra.closeChatModal === "function") {
                sierra.closeChatModal();
            }
            // Pass data to Salesforce chat if available
            const transfer = event.detail;
            if (
                window.embedded_svc &&
                typeof window.embedded_svc.bootstrapEmbeddedService === "function"
            ) {
                if (
                    transfer &&
                    transfer.data &&
                    transfer.data.first_name &&
                    transfer.data.last_name &&
                    transfer.data.email
                ) {
                    window.embedded_svc.settings.prepopulatedPrechatFields = {
                        FirstName: transfer.data.first_name,
                        LastName: transfer.data.last_name,
                        Email: transfer.data.email,
                        Subject: transfer.data.chat_summary, // for now passing in chat_summery in Subject. But this will be changed in future.
                    };
                    if (
                        window.embedded_svc.liveAgentAPI &&
                        typeof window.embedded_svc.liveAgentAPI.startChat === "function"
                    ) {
                        window.embedded_svc.liveAgentAPI.startChat();
                        return;
                    }
                }
                window.embedded_svc.bootstrapEmbeddedService();
            }
        };
        window.addEventListener("sierra-chat-transfer", this._handleSierraTransfer);

        // Notify funnel-header about Sierra chat open/close state
        this._sierraChatContainerObserver = new MutationObserver(() => {
            const isOpen = !!document.querySelector("[data-sierra-chat-container]");
            window.dispatchEvent(
                new CustomEvent("sierra-chat-visibility", { detail: { open: isOpen } })
            );
        });
        this._sierraChatContainerObserver.observe(document.body, {
            childList: true,
            subtree: true,
        });
    },
    beforeUnmount() {
        window.removeEventListener("launch-sierra-webchat", this.triggerSierraChat);
        window.removeEventListener("sierra-chat-transfer", this._handleSierraTransfer);
        if (this._sierraChatContainerObserver) {
            this._sierraChatContainerObserver.disconnect();
        }
    },
};
</script>
