﻿// Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your JavaScript code.

// Track pages opened from Process360Sales campaign emails.
(() => {
    const url = new URL(window.location.href);
    const storageKey = 'p360_campaign_visit';
    const campaignId = url.searchParams.get('p360_visit');
    const [savedId, expiresAt] = (sessionStorage.getItem(storageKey) || '').split('|');
    const storedId = Number(expiresAt) > Date.now() ? savedId : null;
    const sameSiteReferrer = (() => {
        try { return new URL(document.referrer).origin === url.origin; }
        catch { return false; }
    })();
    const isReload = performance.getEntriesByType('navigation')[0]?.type === 'reload';

    if (!campaignId && (!storedId || (!sameSiteReferrer && !isReload))) {
        sessionStorage.removeItem(storageKey);
        return;
    }
    const trackingId = campaignId || storedId;

    if (campaignId) {
        sessionStorage.setItem(storageKey, `${campaignId}|${Date.now() + 2 * 60 * 60 * 1000}`);
        url.searchParams.delete('p360_visit');
        history.replaceState(history.state, '', url.pathname + url.search + url.hash);
    }

    let visitId = null;
    let maxScrollPercent = 0;

    function recordScroll() {
        const pageHeight = Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight || 0);
        const scrollableHeight = pageHeight - window.innerHeight;
        const percent = scrollableHeight <= 0 ? 100 :
            Math.round(Math.min(100, Math.max(0, window.scrollY / scrollableHeight * 100)));
        maxScrollPercent = Math.max(maxScrollPercent, percent);
    }
    async function start() {
        visitId = null;
        try {
            const response = await fetch('/CampaignVisit/Start', {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pageUrl: url.href, trackingId })
            });
            if (response.ok && response.status !== 204) visitId = (await response.json()).visitId;
            else if (campaignId) sessionStorage.removeItem(storageKey);
        } catch (_) { /* Tracking must not interrupt the page. */ }
    }

    function update(beacon = false) {
        if (!visitId) return;
        recordScroll();
        const body = JSON.stringify({ visitId, maxScrollPercent });
        if (beacon && navigator.sendBeacon) {
            navigator.sendBeacon('/CampaignVisit/Update', new Blob([body], { type: 'application/json' }));
            return;
        }
        fetch('/CampaignVisit/Update', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json' },
            body,
            keepalive: beacon
        }).catch(() => { });
    }

    recordScroll();
    window.addEventListener('scroll', recordScroll, { passive: true });
    start();
    setInterval(() => {
        if (document.visibilityState === 'visible') update();
    }, 15000);
    document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'hidden') update(true);
    });
    window.addEventListener('pagehide', () => update(true));
})();
