/**
 * Checkout Pro Analytics: escucha los avisos de Checkout Pro («checkoutpro:event») y los manda
 * en lote al recolector. La visita es un número al azar en sessionStorage: vive solo en esta
 * pestaña, no es una cookie y no dice quién es nadie.
 */
(function () {
    'use strict';

    var cfg = window.cpaConfig;
    if (!cfg || !cfg.url || !window.JSON) {
        return;
    }

    function randomKey() {
        var chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        var out = '';
        var bytes = new Uint8Array(16);
        if (window.crypto && window.crypto.getRandomValues) {
            window.crypto.getRandomValues(bytes);
        } else {
            for (var j = 0; j < 16; j++) {
                bytes[j] = Math.floor(Math.random() * 256);
            }
        }
        for (var i = 0; i < 16; i++) {
            out += chars.charAt(bytes[i] % chars.length);
        }
        return out;
    }

    var key;
    try {
        key = window.sessionStorage.getItem('cpa_visit');
        if (!/^[a-z0-9]{16}$/.test(key || '')) {
            key = randomKey();
            window.sessionStorage.setItem('cpa_visit', key);
        }
    } catch (e) {
        key = randomKey();
    }
    var device = window.matchMedia && window.matchMedia('(max-width: 767px)').matches ? 1 : 2;
    var queue = [];

    function push(ev) {
        ev.t = Date.now();
        queue.push(ev);
        if (queue.length >= 40) {
            flush();
        }
    }

    function flush() {
        if (!queue.length) {
            return;
        }
        var now = Date.now();
        var events = queue.map(function (ev) {
            var out = {y: ev.y, a: now - ev.t};
            ['n', 'p', 'i', 'x'].forEach(function (k) {
                if (ev[k] !== undefined && ev[k] !== null && ev[k] !== '') {
                    out[k] = ev[k];
                }
            });
            return out;
        });
        queue = [];
        var body = JSON.stringify({v: key, d: device, e: events});
        // text/plain: sin consulta previa del navegador; el recolector lee el cuerpo tal cual
        if (navigator.sendBeacon && navigator.sendBeacon(cfg.url, new Blob([body], {type: 'text/plain'}))) {
            return;
        }
        if (window.fetch) {
            window.fetch(cfg.url, {method: 'POST', body: body, keepalive: true, credentials: 'same-origin'}).catch(function () {});
        }
    }

    document.addEventListener('checkoutpro:event', function (e) {
        var d = e.detail || {};
        push({y: d.type, n: d.name, p: d.phase, i: d.id_product, x: d.value});
    });

    // Página de confirmación: el pedido cierra el embudo
    if (window.cpaOrder) {
        push({y: 'order', x: window.cpaOrder.total});
        (window.cpaOrder.products || []).forEach(function (line) {
            push({y: 'order_item', i: line.id, x: line.total});
        });
        flush();
    }

    window.setInterval(flush, 5000);
    window.addEventListener('pagehide', flush);
    document.addEventListener('visibilitychange', function () {
        if (document.visibilityState === 'hidden') {
            flush();
        }
    });
}());
