import {onCLS, onINP, onLCP} from 'https://unpkg.com/web-vitals@4?module';

function isGoodCLS(value) {
    return value < 0.1;
}

function isGoodINP(value) {
    return value < 200;
}

function isGoodLCP(value) {
    return value < 2500;
}

function sendMetricToServer(metricType, metricValue, entries) {
    const data = {
        date: new Date().toISOString(),
        metricType: metricType,
        metricValue: metricValue,
        page: window.location.href,
        entries: entries
    };

    fetch('metric-analytics.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.text())
    .then(result => {
        console.log('Metric sent successfully:', result);
    })
    .catch(error => {
        console.error('Error sending metric:', error);
    });
}

onCLS((metric) => {
    console.log('CLS:', metric.value);
    if (!isGoodCLS(metric.value)) {
        sendMetricToServer('CLS', metric.value, metric.entries);
    }
});

onINP((metric) => {
    console.log('INP:', metric.value);
    if (!isGoodINP(metric.value)) {
        sendMetricToServer('INP', metric.value, metric.entries);
    }
});

onLCP((metric) => {
    console.log('LCP:', metric.value);
    if (!isGoodLCP(metric.value)) {
        sendMetricToServer('LCP', metric.value, metric.entries);
    }
});