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

<script>
import analyticsMixin from "@/mixins/analytics-mixin";
import store from "@/store";
import { routeData } from "@/router/constants/routes";
import { deepClone } from "@/helpers/object-helper";

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",
                    ...this.getSierraContext(),
                },
                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 })
                    ),
            };
        },
        getSierraContext() {
            const glassDamage = store.getters?.order?.damage?.glassToReplace;
            let glassType = "";
            for (let i = 0; i < glassDamage?.length; i++) {
                if (i !== 0) {
                    glassType += "/";
                }
                glassType += glassDamage[i].glassLocation;
            }

            const hasGlassDamage = glassDamage?.length > 0;
            const hasRepairFlag = store.getters.order?.damage?.isRepair;

            let damageType = "";
            if (hasRepairFlag) {
                damageType = "repair";
            } else if (hasGlassDamage) {
                damageType = "replace";
            }

            const isInsurance = store.getters.order?.payment?.isInsurance;

            let paymentType = "";
            if (isInsurance) {
                paymentType = "insurance";
            } else if (isInsurance !== null && isInsurance !== undefined) {
                paymentType = "cash";
            }

            const glassParts = store.getters.order?.lineItems?.glassParts;
            const partNumber = glassParts && glassParts.length > 0 ? glassParts[0].partNumber : "";

            const packageData = deepClone(store.getters?.pageData(routeData.QUOTE.name)?.packages);

            const recalFlag = store.getters?.isRecalibrationOnOrder;
            const displayRecalFlag = glassParts?.length > 0 ? recalFlag : "";

            return {
                current_page: this.pageName,
                vehicle_year: store.getters.order?.vehicle?.year ?? "",
                vehicle_make: store.getters.order?.vehicle?.make ?? "",
                vehicle_model: store.getters.order?.vehicle?.model ?? "",
                vehicle_style: store.getters.order?.vehicle?.style ?? "",
                service_zip: store.getters.order?.serviceLocation?.zipCode ?? "",
                glass_type: glassType ?? "",
                damage_type: damageType ?? "",
                payment_type: paymentType ?? "",
                quote: packageData ?? [],
                part_id: partNumber ?? "",
                recalibration: displayRecalFlag ?? "",
            };
        },
        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,
                    };
                    window.embedded_svc.settings.extraPrechatFormDetails = [
                        {
                            label: "Scarlett AI Summary",
                            value: transfer.data.chat_summary,
                            transcriptFields: ["Scarlett_AI_Summary__c"],
                            displayToAgent: true,
                        },
                    ];
                    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>
