!function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[],_iq:{}};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{var n=function(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}},s=function(e,t,r){return function(n){e._q.push({name:t,args:Array.prototype.slice.call(r,0),resolve:n})}},o=function(e,t,r){e._q.push({name:t,args:Array.prototype.slice.call(r,0)})},i=function(e,t,r){e[t]=function(){if(r)return{promise:new Promise(s(e,t,Array.prototype.slice.call(arguments)))};o(e,t,Array.prototype.slice.call(arguments))}},a=function(e){for(var t=0;t<g.length;t++)i(e,g[t],!1);for(var r=0;r<m.length;r++)i(e,m[r],!0)};r.invoked=!0;var c=t.createElement("script");c.type="text/javascript",c.integrity="sha384-Qht2PEamEOgBr0T73d2XgDN5WYZGrhAy2nyMa193Xra/hWrydUQY4qlwK620MTXj",c.crossOrigin="anonymous",c.async=!0,c.src="https://cdn.amplitude.com/libs/analytics-browser-2.6.3-beta.0-min.js.gz",c.onload=function(){
    e.amplitude.runQueuedFunctions||console.log("[Amplitude] Error: could not load SDK");
    setupAmplitude();
};var u=t.getElementsByTagName("script")[0];u.parentNode.insertBefore(c,u);for(var l=function(){return this._q=[],this},p=["add","append","clearAll","prepend","set","setOnce","unset","preInsert","postInsert","remove","getUserProperties"],d=0;d<p.length;d++)n(l,p[d]);r.Identify=l;for(var f=function(){return this._q=[],this},y=["getEventProperties","setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties"],v=0;v<y.length;v++)n(f,y[v]);r.Revenue=f;var g=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","setOptOut","setTransport","reset","extendSession"],m=["init","add","remove","track","logEvent","identify","groupIdentify","setGroup","revenue","flush"];a(r),r.createInstance=function(e){return r._iq[e]={_q:[]},a(r._iq[e]),r._iq[e]},e.amplitude=r}}(window,document)}();

let dropdownValue;
let sendEmailCategoryValue;
let searchBarClicked = false;
let searchBarClickedResultTitle;
let searchBarClickedResultLinkSource;

const ELEMENT_TYPE_MAP = new Map([
    ['BUTTON', 'Button'],
    ['A', 'Link'],
    ['C-NAVIGATION-MENU', 'Navigation Menu'],
    ['C-TOPIC-HEADER', 'Topic Header'],
    ['LIGHTNING-BUTTON', 'Lightning Button'],
    ['EMBEDDEDSERVICE-CHAT-HEADER', 'Chat Header'],
    ['C-PRE-CHAT-FORM', 'Pre Chat Form'],
    ['C-CONTACT-US', 'Contact Us'],
    ['SUMMARY', 'Accordion'],
    ['VIDEO', 'Video'],
    ['LIGHTNING-BASE-COMBOBOX', 'Lightning Dropdown Element'],
    ['P', 'Paragraph Text'],
    ['IMG', 'Image'],
    ['LI', 'List Element Text'],
    ['H1', 'Heading Text'],
    ['H2', 'Heading Text'],
    ['H3', 'Heading Text'],
    ['H4', 'Heading Text'],
    ['H5', 'Heading Text'],
    ['H6', 'Heading Text'],
    ['SPAN', 'Span Text'],
    ['LIGHTNING-FORMATTED-TEXT', 'Lightning Formatted Text'],
    ['INPUT', 'Input Element'],
    ['LABEL', 'Label Element'],
    ['TEXTAREA', 'Text Area Element'],
    ['DIV', 'Div Element'],
    ['IFRAME', 'iFrame Element'],
    ['LIGHTNING-COMBOBOX', 'Lightning Combobox Dropdown'],
    ['LIGHTNING-PRIMITIVE-ICON', 'Search Element']
]);

function setupAmplitude(){
    //sessionStorage.setItem('previousURL', this.window.location.href);
    sessionStorage.setItem('previousURL', "none");

    amplitude.init("b5118664eac4129f90c995429011ae23", {
        defaultTracking: false,
        serverZone: "EU", 
        autocapture: {
            attribution: true,
            pageViews: false,
            sessions: true,
            formInteractions: false,
            fileDownloads: true,
            elementInteractions: false,
          },
    });
    const deviceIdValue = document.cookie.split('; ').find(cookie => cookie.startsWith('rmMetaV2-device_id='))?.split('=')[1];
    if(deviceIdValue){
        // If there is already a device_id in use, then save that to Amplitude
        amplitude.setDeviceId(deviceIdValue);
    } else {
        // If user is on the Support Page for the first time (and hasn't visited other rm sites), create a device_id
        const deviceId = uuidv4();
        document.cookie = "rmMetaV2-device_id="+deviceId+";domain=.remarkable.com;path=/;";
        amplitude.setDeviceId(deviceId);
    }
}

// Function that generates a UUID device_id if none is available
function uuidv4() {
    return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c => (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16));
}

// Function that parses any UTM parameters passed into the Support Pages
function parseUTMParams() {
    const params = new URLSearchParams(window.location.search);
    const utmParams = {};
    const utmKeys = ['utm_source', 'utm_campaign', 'utm_content', 'utm_medium', 'utm_id', 'utm_term', 'utm_variant'];

    utmKeys.forEach(key => {
        if(params.has(key)){
            utmParams[key] = params.get(key);
        } else {
            utmParams[key] = 'none';
        }
    });
    return utmParams;
}

function getElementText(element) {
    if (!element) return '';
    if (element.nodeType === Node.TEXT_NODE) {
        return element.textContent.trim();
    }
    return Array.from(element.childNodes)
        .map(getElementText)
        .join(' ')
        .trim();
}

function logClickedElement(event) {
    const path = event.composedPath();
    const pathname = window.location.pathname;
    // Use composed path if an element within an LWC has been clicked (hidden by the shadow DOM), otherwise use a regular event.target
    const clickedElement = path && path.length > 0 ? path[0] : event.target;
    const { tagName } = clickedElement;

    let elementType = ELEMENT_TYPE_MAP.get(tagName) || 'Other';
    let elementText;
    let elementLink;

    switch (tagName) {
        // This is for the Category links on the Support Main Page (the Sub-Heading Paragraph Text)
        case 'P':
            if (clickedElement.parentElement?.parentNode?.host.parentNode?.tagName === 'A') {
                elementType = 'Link';
                elementText = getElementText(clickedElement);
                elementLink = clickedElement.parentElement?.parentNode?.host.parentNode?.href;
            }
            break;
        // Category links on the Support Main Page (the Heading Text) - H3
        // Knowledge Article links on the Support Main Page (the Heading Text) - H2
        case 'H6':
        case 'H5':
        case 'H4':
        case 'H3':
        case 'H2':
        case 'H1':
        if (clickedElement.parentElement?.tagName === 'A') {
            elementType = 'Link';
            elementText = getElementText(clickedElement);
            elementLink = clickedElement.parentElement?.href;
        }
            break;
        case 'INPUT':
            elementText = clickedElement.value;
            break;
        case 'A':
            elementType = 'Link';
            elementText = getElementText(clickedElement);
            elementLink = clickedElement.href;
            break;
        case 'BUTTON':
            elementText = getElementText(clickedElement);
            if (elementText === 'Chat with a person' || elementText === 'Chat with our AI agent' || elementText === 'Start chat') {
                elementType = 'Chat Button';
            } else if (elementText === 'Send email') {
                elementType = 'Send Email Button';
            }
            break;
        case 'SPAN':
            elementText = getElementText(clickedElement);
            // This if statement covers Related Article Links (OOTB)
            if (clickedElement.hasAttribute('c-navigationmenuitem_navigationmenuitem')) {
                sendEmailCategoryValue = elementText;
            }
            // Checking one level (parent) above the Span to see if the HTML Tag is an Anchor Link 
            else if (clickedElement.parentElement?.tagName === 'A') {
                elementType = 'Link';
                elementText = getElementText(clickedElement);
                elementLink = clickedElement.parentElement?.href;
            }
            // Checking two level (grandparent) above the Span to see if the HTML Tag is an Anchor Link  - Specifically for Support Home Page Top Articles
            else if (clickedElement.parentElement?.parentNode?.tagName === 'A') {
                elementType = 'Link';
                elementText = getElementText(clickedElement);
                elementLink = clickedElement.parentElement?.parentNode?.href;
            }
            // Checking two levels (grandparent) above the Span to see if the HTML Tag is an Anchor Link 
            else if (clickedElement.parentElement?.parentNode?.host.parentNode?.tagName === 'A') {
                elementType = 'Link';
                elementText = getElementText(clickedElement);
                elementLink = clickedElement.parentElement?.parentNode?.host.parentNode?.href;
            }
            break;
        case 'MARK':
            // This is for catching the OOTB Mark Tag Links on the Search Results Page
            if (clickedElement.parentElement?.tagName === 'SPAN') {
                elementType = 'Link';
                elementText = clickedElement.parentElement?.innerText;
            }
            break;
        case 'IMG':
            elementText = clickedElement.src;
            if (elementText.includes('ThumbsUp')) {
                elementType = 'Thumbs Up Feedback';
            } else if (elementText.includes('ThumbsDown')) {
                elementType = 'Thumbs Down Feedback';
            }
            break;
        case 'LIGHTNING-PRIMITIVE-ICON':
            if (clickedElement.parentElement?.title === 'Expand search') {
                elementType = 'Search Icon Button';
                elementText = 'Search Icon Button';
            }
            break;
        case 'LABEL':
            elementText = getElementText(clickedElement);
            if (clickedElement.className === 'collapseLabel' && (elementText === 'Collapse All' || elementText === 'Expand All')) {
                elementType = 'Button';
            }
            break;
        default:
            elementText = getElementText(clickedElement);
    }

    if (elementType === 'Chat Button') {
        const eventChatProperties = {
            action: elementText,
            question_type: dropdownValue,
            current_page_url: pathname,
            current_pathname: this.window.location.href,
            origin: sessionStorage.getItem('previousURL')
        };
        amplitude.track('Chat Started', eventChatProperties);
    } else if (elementType === 'Send Email Button') {
        const eventChatProperties = {
            email_category: sendEmailCategoryValue,
            current_pathname: pathname,
            current_page_url: this.window.location.href,
            origin: sessionStorage.getItem('previousURL')
        };
        amplitude.track('Email Sent', eventChatProperties);
    } else if((tagName === 'BUTTON' || tagName === 'A' || tagName === 'SUMMARY' || elementType === 'Thumbs Up Feedback' || elementType === 'Thumbs Down Feedback' || tagName === 'COMMUNITY_ARTICLE-SIMILAR-ARTICLES-ITEM' || elementType === 'Search Icon Button' || elementType === 'Link' || elementType === 'Button') && searchBarClicked === false && elementText !== 'Select an Option') {
        // Only track events in Amplitude for clickable events (Accordions, Feedback Thumbs Up/Down images, links, or Buttons)
        const eventProperties = {
            type: elementType,
            text: elementText,
            current_pathname: pathname, 
            current_page_url: this.window.location.href,
            link_source: elementLink || "none",
            origin: sessionStorage.getItem('previousURL')
        };
        amplitude.track('Element Clicked', eventProperties);
    }
    if(searchBarClicked){
        searchBarClicked = false;
        searchBarClickedResultTitle = '';
        searchBarClickedResultLinkSource = '';
    }
}

window.addEventListener('click', logClickedElement, true);

// This gets fired before the page changes, and saves the previousURL in Session storage to be used for the origin value
window.navigation.addEventListener("navigate", (event) => {
    let currentURL = this.window.location.href;
    previousURL = sessionStorage.getItem('previousURL');

    if(currentURL !== previousURL){
        sessionStorage.setItem('previousURL', currentURL);
    }
});

// Mousedown Event Listener to capture Search Box events (the OOTB search results box appearing)
window.addEventListener("mousedown", (event) => {
    if(event.target.parentElement?.className.startsWith('search-')){
        searchBarClicked = true;
        searchBarClickedResultTitle = event.target.parentElement?.title;
    } else {
        searchBarClicked = false;
        searchBarClickedResultTitle = '';
        searchBarClickedResultLinkSource = '';
    }
});

// Save a Page View event everytime the page loads
window.addEventListener('load', (event) => {
    trackPageView();
});

window.navigation.addEventListener('navigate', (event) => {
    const pathname = window.location.pathname;

    // Track Clicked Links in Search Bar Results before the Page View Event fires for navigation
    if(searchBarClicked){ 
        const url = new URL(event.destination.url);
        searchBarClickedResultLinkSource = url.href;
        const eventProperties = {
            type: 'Link',
            text: searchBarClickedResultTitle,
            current_pathname: pathname, 
            current_page_url: this.window.location.href,
            link_source: searchBarClickedResultLinkSource || "none",
            origin: sessionStorage.getItem('previousURL')
        };
        amplitude.track('Element Clicked', eventProperties);
    }
})

// After the Page has successfully navigated to another Page, save the Page Viewed Event in Amplitude
window.navigation.addEventListener('navigatesuccess', (event) => {
    trackPageView();
});

// This has been commented for now, to avoid additional Page Viewed events from being triggered, but this may be used in the future
// If the User was away from the browser/tab, but now returned, fire a Page Viewed Event
// document.addEventListener('visibilitychange', function() {
//     if (document.visibilityState === 'visible') {
//         trackPageView();
//     } 
// });

// This function keeps a track of each Page Viewed on the Support Pages
function trackPageView(){
    let urlObject;
    let referrerDomain;
    // In some cases, the document.referrer will be empty (if a user directly types the URL in the address bar, uses a bookmark, or opens a new tab and pastes a URL)
    if(document.referrer !== ''){
        urlObject = new URL(document.referrer);
        referrerDomain = urlObject.hostname;
    }
    // UTM Param Parsing
    const utmParams = parseUTMParams();
    let utm_source, utm_medium, utm_id, utm_campaign, utm_content, utm_term;


    if(Object.keys(utmParams).length !== 0){
        const cookieValue = JSON.stringify(utmParams);
        // Replace cookie with passed in params
        document.cookie = 'rmMetaV2-utm_parameters='+cookieValue;

        // Save UTM params to Amplitude
        utm_source = utmParams.utm_source;
        utm_medium = utmParams.utm_medium;
        utm_id = utmParams.utm_id;
        utm_campaign = utmParams.utm_campaign;
        utm_content = utmParams.utm_content;
        utm_term = utmParams.utm_term;
    }

    // Saving and setting the utm parameters to be placed underneath the User Properties in Ampltiude
    // This is to track when a user comes to the page, all the events that happen afterwords that all sourced from specific utm parameters
    const identifyObj = new amplitude.Identify();
    identifyObj.set('utm_id', utm_id || 'none');
    identifyObj.set('utm_source', utm_source || 'none');
    identifyObj.set('utm_medium', utm_medium || 'none');
    identifyObj.set('utm_campaign', utm_campaign || 'none');
    identifyObj.set('utm_content', utm_content || 'none');
    identifyObj.set('utm_term', utm_term || 'none');
    amplitude.identify(identifyObj);

    // Setting a 1.8 second timeout before a Page Viewed event is saved in Amplitude, to allow for Salesforce Object Pages
    // (for example: Article Detail or Topic Detail) to load the record and get the accurate title, instead of the title of the Page itself from the builder
    setTimeout(() => {
        amplitude.track('Page Viewed', {
            current_pathname: this.window.location.pathname,
            current_page_title: document.title,
            current_page_url: this.window.location.href,
            referrer: document.referrer || 'none',
            referring_domain: referrerDomain || 'none',
            origin: sessionStorage.getItem('previousURL'), 
            utm_id: utm_id || 'none',
            utm_source: utm_source || 'none',
            utm_medium: utm_medium || 'none',
            utm_campaign: utm_campaign || 'none',
            utm_content: utm_content || 'none',
            utm_term: utm_term || 'none'
        });
    }, 1800);
}

window.addEventListener('change', logDropdownElement);

// For logging inputted text for the Search Bars
const debouncedKeyHandler = debounce(logInputtedElement, 1000);
window.addEventListener('input', debouncedKeyHandler);

// Used to track any dropdown events within an LWC
function logDropdownElement(event) {
    const path = event.composedPath();
    const clickedDropdownElement = path && path.length > 0 ? path[0].value : event.target.value;

    if(path && path.length > 0 && path[0].tagName === "LIGHTNING-COMBOBOX"){
        dropdownValue = clickedDropdownElement;
    }
}

// Function used solely for the Search Bars on the Support Pages, to track what the user inputted as the Search Query and what the Origin (previous URL) was
function logInputtedElement(event) {
    const origin = sessionStorage.getItem('previousURL');
    const pathname = window.location.pathname;
    const path = event.composedPath();
    const clickedElement = path && path.length > 0 ? path[0] : event.target;
    const { tagName } = clickedElement;
    const inputtedElementValue = clickedElement.value;

    // Avoid logging for any extra elements that are not search bars and only specific to OOTB Search Bars
    if(tagName === 'INPUT' && clickedElement.classList.contains('search-input') && 
        tagName !== 'C-SUBMIT-FEEDBACK' && tagName !== 'TEXTAREA' && tagName !== 'LABEL' && tagName !== 'C-ARTICLE-BODY-ACCORDION' && tagName !== 'C-CONTACT-SUPPORT-FORM' && tagName !== 'FLOWRUNTIME-FLOW'){
        const eventChatProperties = {
            origin: origin,
            current_pathname: pathname,
            current_page_url: this.window.location.href,
            query: inputtedElementValue
        };
        amplitude.track('Search Query Executed', eventChatProperties);
    }
}

function debounce(func, delay) {
    let timeout;
    return function(...args) {
        const context = this;
        clearTimeout(timeout); 
        timeout = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}