<template>
    <div class="funnel-header" :class="{ scrolled: isScrolled }" v-if="imageSrc">
        <div class="d-flex w-100">
            <progress-bar :page="$route.name" />
        </div>
        <div class="container d-flex">
            <div class="site-logo">
                <a href="https://safelite.com">
                    <img class="logo-image img-fluid" :src="imageSrc" alt="Safelite logo" />
                </a>
            </div>
            <div class="button-container webchat">
                <span class="webchat d-flex">
                    <button
                        v-show="shouldShowWebchatButton"
                        v-on:click="webchatClicked"
                        type="button"
                        class="chat-button">
                        <span>Chat Now</span>
                    </button>
                </span>
            </div>
            <div class="button-container">
                <menuModal />
            </div>
        </div>
    </div>
    <template v-for="globalAlert in globalAlertMessages" :key="globalAlert.id">
        <div class="container d-flex global-alert-wrapper">
            <transition name="fade" mode="out-in">
                <alert
                    v-if="globalAlert.displayAlert"
                    class="rounded-0 w-100 border-0 shadow-sm"
                    cmsWidgetName="GlobalAlert"
                    :manualHeadline="globalAlert.messageHeadline"
                    :manualCopy="globalAlert.messageCopy"
                    :alertClass="globalAlert.type"
                    v-bind:isDismissible="globalAlert.isDismissible" />
            </transition>
        </div>
    </template>
</template>

<script>
import alert from "@/ux-components/alert/alert";
import eventBus from "@/helpers/event-bus/event-bus";
import { globalEvents } from "@/constants/events";
import menuModal from "@/fmg-components/funnel-header/menu-modal/menu-modal";
import progressBar from "@/fmg-components/funnel-header/progress-bar/progress-bar";
import { webchatHelper } from "@/helpers/webchat-helper";
import store from "@/store";

// Constants
const ALERT_DURATION = 3000; // millisecond time to display alert before dismissal

export default {
    name: "funnel-header",
    data() {
        return {
            globalAlertMessages: [],
            sierraChatOpen: false,
            salesforceChatOpen: false,
            isSalesforceTransferInProgress: false,
            isScrolled: false,
        };
    },
    props: {
        cmsWidgetName: String,
        shouldHideWebchatButtonOnPage: {
            type: Boolean,
            default: false,
        },
    },
    setup() {
        const { webchatGlobalNonpersistedState, launchWebchat } = webchatHelper();
        return { webchatGlobalNonpersistedState, launchWebchat };
    },
    computed: {
        imageSrc() {
            return this.getCmsContent(this.cmsWidgetName, "LogoImage");
        },
        shouldShowWebchatButton() {
            // Hide the chat icon if Sierra chat is open
            if (this.sierraChatOpen) {
                return false;
            }
            // Hide the chat icon if Salesforce chat is open or transfer is in progress
            if (this.salesforceChatOpen || this.isSalesforceTransferInProgress) {
                return false;
            }
            // Show if either Sierra is enabled or Salesforce button is available and not hidden by page
            return (
                (this.webchatGlobalNonpersistedState.shouldLaunchSierra ||
                    this.webchatGlobalNonpersistedState.showWebchatButton) &&
                !this.shouldHideWebchatButtonOnPage
            );
        },
    },
    methods: {
        pushGlobalAlert(alertToPush, isAutoDismissing) {
            alertToPush.displayAlert = true;
            alertToPush.id = crypto.randomUUID();
            if (isAutoDismissing) {
                setTimeout(() => {
                    alertToPush.displayAlert = false;
                    // force a re-evaluation of the globalAlertMessages to detect the v-if change
                    this.globalAlertMessages = this.globalAlertMessages.splice(0);
                }, ALERT_DURATION);
            }
            this.globalAlertMessages.push(alertToPush);
        },
        removeGlobalAlert(alertId) {
            const alertIndex = this.globalAlertMessages.findIndex((alert) => alert.id === alertId);
            if (alertIndex !== -1) {
                this.globalAlertMessages.splice(alertIndex, 1);
            }
        },
        getGlobalAlerts() {
            return this.globalAlertMessages;
        },
        webchatClicked(event) {
            event.preventDefault();
            this.launchWebchat();
            // Only set sierraChatOpen if Sierra experiment is active
            if (this.webchatGlobalNonpersistedState.shouldLaunchSierra) {
                this.sierraChatOpen = true;
            }
        },
        syncSierraExperimentFlag() {
            const experiments = store.getters.applicationUser.experiments;
            const sierraExp = experiments?.find(
                (exp) =>
                    exp.universeName === "CONTENT_FMG_SierraWebchat" &&
                    exp.settings?.UseSierraChat === "true"
            );
            this.webchatGlobalNonpersistedState.shouldLaunchSierra = !!sierraExp;
        },
    },
    components: {
        alert,
        menuModal,
        progressBar,
    },
    mounted() {
        this.syncSierraExperimentFlag();
        // Check if alert event is on the bus
        const alertEvent = eventBus.readAndPopEventFromBus(
            globalEvents.Categories.GLOBAL_ALERT,
            globalEvents.SubCategories.PAGE_NOT_FOUND
        );
        // If alert event is on the bus, then display the alert
        if (alertEvent !== undefined) {
            alertEvent.displayAlert = true;
            this.globalAlertMessages.push(alertEvent);
        }

        //Uknown alerts most likely were added by a failed api call in global-methods
        const unknownAlertEvent = eventBus.readAndPopEventFromBus(
            globalEvents.Categories.GLOBAL_ALERT,
            globalEvents.SubCategories.UNKNOWN_ERROR
        );

        if (unknownAlertEvent !== undefined) {
            unknownAlertEvent.displayAlert = true;
            this.globalAlertMessages.push(unknownAlertEvent);
        }
        // Listen for Sierra chat open/close events from sierra-webchat
        this._handleSierraChatVisibility = (event) => {
            this.sierraChatOpen = !!(event.detail && event.detail.open);
            if (this.sierraChatOpen) {
                this.isSalesforceTransferInProgress = false;
            }
        };
        window.addEventListener("sierra-chat-visibility", this._handleSierraChatVisibility);

        // Listen for Salesforce chat open/close events from salesforce-webchat
        this._handleSalesforceChatVisibility = (event) => {
            this.salesforceChatOpen = !!(event.detail && event.detail.open === true);
        };
        window.addEventListener("salesforce-chat-visibility", this._handleSalesforceChatVisibility);

        // Listen for transfer event to set transfer-in-progress flag
        this._handleSierraToSalesforceTransfer = () => {
            this.isSalesforceTransferInProgress = true;
        };
        window.addEventListener("sierra-chat-transfer", this._handleSierraToSalesforceTransfer);

        // Reset transfer flag when Salesforce chat opens
        this._handleSalesforceChatOpened = (event) => {
            if (event.detail && event.detail.open === true) {
                this.isSalesforceTransferInProgress = false;
                this.salesforceChatOpen = true;
            } else {
                this.salesforceChatOpen = false;
            }
        };
        window.addEventListener("salesforce-chat-visibility", this._handleSalesforceChatOpened);

        // Add scroll listener for header shadow effect
        this._handleScroll = () => {
            this.isScrolled = window.scrollY > 0;
        };
        window.addEventListener("scroll", this._handleScroll);
    },
    beforeUnmount() {
        window.removeEventListener("sierra-chat-closed", this._handleSierraChatClosed);
        window.removeEventListener("sierra-chat-visibility", this._handleSierraChatVisibility);
        window.removeEventListener(
            "salesforce-chat-visibility",
            this._handleSalesforceChatVisibility
        );
        window.removeEventListener("sierra-chat-transfer", this._handleSierraToSalesforceTransfer);
        window.removeEventListener("salesforce-chat-visibility", this._handleSalesforceChatOpened);
        window.removeEventListener("scroll", this._handleScroll);
    },
};
</script>

<style lang="scss" scoped>
.funnel-header {
    .container {
        padding: 1rem 0.75rem;
        display: flex;
        align-items: center;
        @include media-breakpoint-up(md) {
            padding: 2rem 0.75rem;
        }
    }
    position: sticky;
    top: 0;
    z-index: 1000;
    background-color: white;
    box-shadow: none;
    transition: box-shadow 0.3s ease-in-out;
    padding: 0;

    &.scrolled {
        box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.2);
    }

    .button-container {
        &.webchat {
            margin-right: 0.875rem;
        }
    }

    .site-logo {
        margin-right: auto;
    }

    .logo-image {
        width: 100px;
        height: auto;
        margin: 0 auto;
        @include media-breakpoint-up(md) {
            width: 165px;
        }
    }

    .webchat {
        .chat-button {
            text-transform: uppercase;
            width: 7.5rem;
            height: 2rem;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' id='Layer_2' x='0' y='0' style='enable-background:new 0 0 24 24' version='1.1' viewBox='0 0 24 24'%3E%3Cstyle%3E .st0%7Bfill:%232e6fb6%7D %3C/style%3E%3Ccircle cx='12' cy='12' r='12' class='st0'/%3E%3Cpath d='M18.3 12c0 3.5-2.8 6.3-6.3 6.3-1.2 0-2.4-.4-3.4-1l-2.3.7s-.5.1-.3-.4.5-1.7.7-2.2c-.6-1-1-2.1-1-3.3 0-3.5 2.8-6.3 6.3-6.3 3.5-.1 6.3 2.7 6.3 6.2z' style='fill:%23fff'/%3E%3Ccircle cx='10.2' cy='12' r='.6' class='st0'/%3E%3Ccircle cx='12' cy='12' r='.6' class='st0'/%3E%3Ccircle cx='13.8' cy='12' r='.6' class='st0'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-size: 2rem 2rem;
            background-position: right;
            border: none;
            background-color: transparent;
            padding-right: 2rem;
            font-size: 0.875rem;
            font-weight: 600;
            font-family: "UrbanistSemibold";
            color: $blue;
            @include media-breakpoint-down(md) {
                width: 2rem;
                padding-right: 0;
            }
            span {
                @include media-breakpoint-down(md) {
                    display: none;
                }
            }
        }
    }
}
.global-alert-wrapper .alert {
    margin: 1rem 0 1.5rem;

    @include media-breakpoint-up(md) {
        margin-top: 0;
    }
}
</style>
