(function () {
    'use strict';

    if (!window.wncAnalytics || !window.wncAnalytics.endpoint) {
        return;
    }

    document.addEventListener('click', function (event) {
        var button = event.target.closest('.wnc-button[data-wnc-post-id]');

        if (!button) {
            return;
        }

        var data = new FormData();
        data.append('action', window.wncAnalytics.action || 'wnc_track_click');
        data.append('post_id', button.getAttribute('data-wnc-post-id') || '');
        data.append('button_mode', button.getAttribute('data-wnc-button-mode') || 'url');

        if (navigator.sendBeacon) {
            navigator.sendBeacon(window.wncAnalytics.endpoint, data);
            return;
        }

        fetch(window.wncAnalytics.endpoint, {
            method: 'POST',
            body: data,
            credentials: 'same-origin',
            keepalive: true
        }).catch(function () {});
    }, { passive: true });
}());
