"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listenersAreAttached = void 0;
exports.attachListeners = attachListeners;
const web_vitals_1 = require("web-vitals");
const POLLING_MAX_ATTEMPTS = 10;
const POLLING_INTERVAL_MILLIS = 100;
exports.listenersAreAttached = false;
function attachListeners() {
    (0, web_vitals_1.onCLS)(sendMetric);
    (0, web_vitals_1.onFCP)(sendMetric);
    (0, web_vitals_1.onLCP)(sendMetric);
    (0, web_vitals_1.onTTFB)(sendMetric);
    onNavigationEvent(sendMetric);
    exports.listenersAreAttached = true;
}
function handleNavigationEvent(eventName, callback) {
    const performanceEntries = performance.getEntriesByType('navigation');
    const navigationTiming = performanceEntries?.[0];
    const eventTimestamp = navigationTiming?.[eventName];
    callback({
        name: eventName,
        value: eventTimestamp,
        delta: eventTimestamp,
        rating: 'none',
        id: `NAV:${eventName}:${eventTimestamp}:${Date.now()}`,
        entries: performanceEntries?.map((entry) => entry?.toJSON()),
        navigationType: navigationTiming?.type ?? 'navigate',
    });
}
function pollForEventTimestamp(eventName, callback, navigationTiming) {
    navigationTiming =
        navigationTiming ??
            performance.getEntriesByType('navigation')?.[0];
    if (navigationTiming?.[eventName]) {
        handleNavigationEvent(eventName, callback);
        return;
    }
    let attempts = 0;
    const interval = window.setInterval(() => {
        attempts++;
        const navigationTiming = performance.getEntriesByType('navigation')?.[0];
        if (navigationTiming?.[eventName] || attempts >= POLLING_MAX_ATTEMPTS) {
            handleNavigationEvent(eventName, callback);
            window.clearInterval(interval);
        }
    }, POLLING_INTERVAL_MILLIS);
}
function onNavigationEvent(callback) {
    const navigationTiming = performance.getEntriesByType('navigation')?.[0];
    if (navigationTiming !== undefined) {
        handleNavigationEvent('startTime', callback);
    }
    if (navigationTiming?.domContentLoadedEventEnd) {
        handleNavigationEvent('domContentLoadedEventEnd', callback);
    }
    else {
        document.addEventListener('DOMContentLoaded', function () {
            pollForEventTimestamp('domContentLoadedEventEnd', callback);
        });
    }
}
const sendMetric = (metric) => {
    const navigationTiming = performance.getEntriesByType('navigation')?.[0];
    window.dispatchMablEvent?.({
        createdTime: Date.now(),
        timeOrigin: performance.timeOrigin,
        type: 'WEB_PERFORMANCE_METRIC_DETECTED',
        currentUrl: window.document.URL,
        navigationUrl: navigationTiming?.name,
        metric,
    });
};
