/**
 * Created by : Mohammed Imran (mohammed.imran@cloud.com)
 * Insights tracking for Coveo search engine and result page
 */

window.addEventListener(
    "load",
    function () {
        if (window.location.href.indexOf('/global-search/') > -1) {

            console.log("Coveo search page detected");

            (function () {

                const searchButton = document.querySelector(".CoveoSearchButton");
                var userId = getUserId(); // Assign userId globally

                function getUserId() {
                    let sessionKeys = sessionStorage.getItem('LSSIndex:SESSION{"namespace":"c"}');
                    let sessionKeyObj = JSON.parse(sessionKeys);
                    var sessionKey = sessionKeyObj.user_id; // Assuming 'user_id' is the key in sessionStorage

                    // Retrieve the value from sessionStorage
                    var userId = sessionStorage.getItem(sessionKey);

                    // Check if the value exists
                    if (userId == null || userId === undefined || userId === "undefined") {
                        return 'anonymous'; // Return 'anonymous' if userId doesn't exist
                    } else {
                        return userId; // Return userId if it exists
                    }
                }

                function handleHashChange() {
                    const startingUrl = window.location.href;
                    const myUrl = new URL(startingUrl);
                    const hash = new URLSearchParams(myUrl.hash.substring(1));
                    const searchText = hash.get("q");
                    if (searchButton) {
                        sendInsightsEvents(userId, "interacted", "search keyword", {
                            searchText: searchText,
                            searchEngine: "coveo",
                        });
                    }
                    console.log("Search text:", searchText);
                    console.log("User Id :", userId);
                }

                // Initial execution if hash is already present on page load
                handleHashChange();

                // Check if the element exists
                if (searchButton) {
                    // Add a click event listener to the anchor link
                    searchButton.addEventListener("click", function (event) {
                        handleHashChange();
                    });
                }

                document.addEventListener('click', function (event) {
                    var clickedLink = event.target.closest('a');
                    if (clickedLink) {
                        event.stopPropagation(); // Stop event from bubbling further
                        const startingUrl = window.location.href;
                        const myUrl = new URL(startingUrl);
                        const hash = new URLSearchParams(myUrl.hash.substring(1));
                        const searchText = hash.get("q");
                        var LinkTitle = clickedLink.getAttribute('title');
                        var LinkHref = clickedLink.getAttribute('href');
                        console.log("Search result title: ", LinkTitle);
                        console.log("Search result link: ", LinkHref);
                        sendInsightsEvents(userId, 'clicked', 'search results', {
                            searchResultTitle: LinkTitle,
                            searchResultLink: LinkHref,
                            searchText: searchText,
                            searchEngine: "coveo"
                        });
                    }
                });

                // Track the previous value of the 'q' parameter
                let previousQ = new URLSearchParams(window.location.hash.substring(1)).get("q");

                // Check if the 'q' parameter has changed and call handleHashChange if it has
                function checkUrlAndHandleHashChange() {
                    const currentQ = new URLSearchParams(window.location.hash.substring(1)).get("q");
                    if (currentQ !== previousQ) {
                        previousQ = currentQ;
                        handleHashChange();
                    }
                }

                // Override history.pushState and history.replaceState
                const originalPushState = history.pushState;
                const originalReplaceState = history.replaceState;

                history.pushState = function (...args) {
                    originalPushState.apply(this, args);
                    checkUrlAndHandleHashChange();
                };

                history.replaceState = function (...args) {
                    originalReplaceState.apply(this, args);
                    checkUrlAndHandleHashChange();
                };

                // Add event listener for hashchange
                window.addEventListener("hashchange", checkUrlAndHandleHashChange);
                window.addEventListener("popstate", checkUrlAndHandleHashChange);
            })();
        }
    },
    !1
);