/* eslint-disable @lwc/lwc/no-document-query */
// SEO: Add meta description to Guides
document.addEventListener("ZMSetMetadata", (e) => {
    createMetaTag("description", e.detail.description);
});

// Listen for event from Guides to report product tags to Google Analytics
document.addEventListener("ZMSetMetadataLabels", e => {
    if(!e.detail?.length) return;

    let valueTags = [];
    e.detail.forEach(metadata => {
        if(metadata.content && (metadata.name === 'Product' || metadata.name === 'Integration')) {
            valueTags = valueTags.concat(metadata.content.split(';').map(tag => tag.split(',')[1].trim()));
        }
    });
    if(valueTags.length > 0) {
        window.dataLayer.push({ 
            event: "supportContentTags", 
            tags: valueTags.join(',')
        });
    }
});

// Hide or show Qualtrics Feedback button based on url
// This is needed because Qualtrics targeting logic is not triggered on page change
function showHideQualtrics() {
    const qualtricsButtonElements = document.querySelectorAll('.QSIFeedbackButton');
    const href = window.location.href;
    // Only show on Guide or Article page
    const logic = href.includes('/s/document-item') || href.includes('s/articles');
    if(qualtricsButtonElements.length && logic) { 
        qualtricsButtonElements.forEach(el => {
            el.style.display = 'initial'; // manually show button 
        });
    } else if(qualtricsButtonElements.length) {
        qualtricsButtonElements.forEach(el => {
            el.style.display = 'none'; // manually hide button 
        });
    }
}

//Monitor change in document title to report updated title to Google Analytics
let supportPageviewTimeout;
const originalDocumentTitle = document.title;
let votingListener = false;
const pageTitleObserver = new MutationObserver(() => {
    if (document.title !== originalDocumentTitle) {  
        showHideQualtrics(); // Hide the Feedback button on subsequent pages if its already shown

        clearTimeout(supportPageviewTimeout);
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        supportPageviewTimeout = setTimeout(() => {
            window.dataLayer.push({ event: "supportPageview", pageTitle: document.title });
            clearTimeout(supportPageviewTimeout);
        }, 3000);
    }

    //DSC Voting
    const dscVoting = document.querySelector("c-dsc-voting");
    if (!dscVoting) return; //Only try to add the listener if the element exists
    dscVoting?.refresh();

    if (votingListener) return; // Only add listener if it doesn't exist yet
    votingListener = true;
    //Add a listener for the voting event: which happens when user votes
    dscVoting.addEventListener("dscvote", (e) => {
        if (!window.dataLayer) {
            console.error("Voting Error: window.dataLayer does not exist.");
            return; //Do not push to data layer unless it exists
        }

        window.dataLayer.push({ event: "supportFeedback", ...e.detail });
    });
});
pageTitleObserver.observe(document.querySelector("title"), { childList: true });

//Account for fixed header to support deep links
window.addEventListener("dscEventDispatcherLoad", () => {
    const fixedHeader = document.querySelector(".themeLayoutStarterWrapper.isHeaderPinned-true");
    if (!fixedHeader) return;

    const headerHeight = fixedHeader.querySelector(".header")?.offsetHeight;

    const html = document.querySelector("html");
    if (!html) return;

    html.style.scrollPaddingTop = `${headerHeight}px`;
});

//Common listener for when components want to create meta tags
document.addEventListener("analytics_lwc_meta_ready", e => {
    createMetaTag(e?.detail?.name, e?.detail?.content);
});

//Listener for DataCategorySelections (Tags) on Knowledge Articles
document.addEventListener("analytics_lwc_report_tags", e => {
    window.dataLayer.push({ event: "supportContentTags", ...e.detail });
});

//Utility Methods
function createMetaTag(name, content) {
    if (!name || !content) return; // Do not create meta tag without valid values

    let el = document.querySelector(`meta[name="${name}"]`);
    // Create meta if it does not already exist
    if (!el) {
        el = document.createElement("META");
        el.setAttribute("name", name);
    }
    el.setAttribute("content", content);
    document.head.appendChild(el);
}
