/**
 * Copyright since 2026 Ecom Experts
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License version 3.0
 * that is bundled with this package in the file LICENSE.md.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/AFL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author    Ecom Experts <ecomyseo@gmail.com>
 * @copyright Since 2026 Ecom Experts
 * @license   https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
 */

// Helpers defensivos: si por orden de carga gtm_core.js no se ha ejecutado todavia,
// definimos versiones minimas para que los pushes no fallen con TypeError.
window.dataLayer = window.dataLayer || [];
if (typeof window.psEventId !== 'function') {
    window.psEventId = function () {
        return 'ps_' + (new Date()).getTime() + '_' + Math.random().toString(36).substr(2, 6);
    };
}
if (typeof window.getConsentState !== 'function') {
    window.getConsentState = function () {
        try {
            var m = document.cookie.match(/(?:^|;\s*)analytics_storage=([^;]+)/);
            return (m && m[1] === 'granted') ? 'granted' : 'denied';
        } catch (e) { return 'denied'; }
    };
}
if (typeof window.getCommonEventParams !== 'function') {
    window.getCommonEventParams = function () {
        return { event_source: 'web', send_to_server: true, consent_state: window.getConsentState() };
    };
}

function ddGtmEventsRun() {
    window.dataLayer = window.dataLayer || [];

    // Process Backend Events (Login, Sign Up)
    if (typeof gtm_backend_events !== 'undefined') {
        var backendEvents = Array.isArray(gtm_backend_events) ? gtm_backend_events : [gtm_backend_events];
        backendEvents.forEach(function (eventData) {
            var common = window.getCommonEventParams();
            if (!eventData.hasOwnProperty('event_id')) {
                eventData['event_id'] = window.psEventId();
            }
            if (!eventData.hasOwnProperty('event_source')) {
                eventData['event_source'] = common.event_source;
            }
            if (!eventData.hasOwnProperty('send_to_server')) {
                eventData['send_to_server'] = common.send_to_server;
            }
            if (!eventData.hasOwnProperty('consent_state')) {
                eventData['consent_state'] = common.consent_state;
            }

            // Universal User Properties Injection
            var userProperties = {};
            if (typeof userid !== 'undefined' && userid) {
                userProperties['user_id'] = userid;
                userProperties['visitor_type'] = 'logged_in';
            } else {
                userProperties['visitor_type'] = 'guest';
            }
            if (typeof recurrent_customer !== 'undefined') {
                userProperties['recurrent'] = recurrent_customer ? 'yes' : 'no';
            }
            eventData['user_properties'] = userProperties;
            // Also flatten them
            for (var prop in userProperties) {
                eventData[prop] = userProperties[prop];
            }

            window.dataLayer.push(eventData);
        });
    }

    // Process Ecommerce Data (Product Views, Purchases)
    window.__ddFiredEvents = window.__ddFiredEvents || {};
    if (typeof gtm_ecommerce_data !== 'undefined') {
        var itemsToPush = Array.isArray(gtm_ecommerce_data) ? gtm_ecommerce_data : [gtm_ecommerce_data];

        itemsToPush.forEach(function (eventData) {
            // Guard: si ya se ha disparado este evento (sesion), saltar para evitar duplicados.
            try {
                var dedupeKey = null;
                if (eventData && eventData.event === 'view_item' && eventData.ecommerce && Array.isArray(eventData.ecommerce.items) && eventData.ecommerce.items[0]) {
                    dedupeKey = 'view_item_' + eventData.ecommerce.items[0].item_id;
                } else if (eventData && eventData.event === 'purchase' && eventData.ecommerce && eventData.ecommerce.transaction_id) {
                    dedupeKey = 'purchase_' + eventData.ecommerce.transaction_id;
                }
                if (dedupeKey) {
                    if (window.__ddFiredEvents[dedupeKey]) return;
                    window.__ddFiredEvents[dedupeKey] = true;
                }
            } catch (e) {}
            // Apply Common Params (Event ID, Source)
            // CRITICAL: Do NOT override event_id if PHP already provided one (e.g. purchase, view_item)
            var common = window.getCommonEventParams();

            // Apply all common params EXCEPT event_id if already present
            if (!eventData.hasOwnProperty('event_id')) {
                eventData['event_id'] = window.psEventId();
            }
            if (!eventData.hasOwnProperty('event_source')) {
                eventData['event_source'] = common.event_source;
            }
            if (!eventData.hasOwnProperty('send_to_server')) {
                eventData['send_to_server'] = common.send_to_server;
            }
            if (!eventData.hasOwnProperty('consent_state')) {
                eventData['consent_state'] = common.consent_state;
            }
            // Inject UserID if not present
            if (!eventData.hasOwnProperty('UserID') && typeof userid !== 'undefined' && userid) {
                eventData['UserID'] = userid;
            }
            // Inject user_data if not present
            if (!eventData.hasOwnProperty('user_data') && typeof $dataeh !== 'undefined') {
                if ($dataeh.hasOwnProperty('user_data')) {
                    eventData['user_data'] = $dataeh.user_data;
                } else {
                    eventData['user_data'] = $dataeh;
                }
            }

            // Universal User Properties Injection for Ecom
            var userProperties = {};
            if (typeof userid !== 'undefined' && userid) {
                userProperties['user_id'] = userid;
                userProperties['visitor_type'] = 'logged_in';
            } else {
                userProperties['visitor_type'] = 'guest';
            }
            if (typeof recurrent_customer !== 'undefined') {
                userProperties['recurrent'] = recurrent_customer ? 'yes' : 'no';
            }
            eventData['user_properties'] = userProperties;
            // Also flatten them for direct Event Parameter pickup
            for (var prop in userProperties) {
                eventData[prop] = userProperties[prop];
            }

            window.dataLayer.push(eventData);
        });
    }

    // Search event (GA4)
    if (typeof dd_search_event !== 'undefined' && dd_search_event && dd_search_event.search_term) {
        try {
            var searchKey = 'search_' + dd_search_event.search_term;
            if (!window.__ddFiredEvents[searchKey]) {
                window.__ddFiredEvents[searchKey] = true;
                var commonS = window.getCommonEventParams();
                window.dataLayer.push({
                    event: 'search',
                    event_id: window.psEventId(),
                    event_source: commonS.event_source,
                    send_to_server: commonS.send_to_server,
                    consent_state: commonS.consent_state,
                    search_term: dd_search_event.search_term,
                    search_results: dd_search_event.search_results
                });
            }
        } catch (e) {}
    }

    // Promociones GA4: auto-detecta banners con data-attrs y emite view_promotion (IntersectionObserver) + select_promotion (click).
    // El comerciante anota su banner asi:
    //   <div data-dd-promotion-id="promo_summer_25" data-dd-promotion-name="Rebajas verano" data-dd-creative-name="hero_top" data-dd-creative-slot="home_top">...</div>
    // Sin ese marcado el codigo no hace nada (zero coste).
    function ddBuildPromoPayload(el, eventName) {
        return {
            event: eventName,
            event_id: window.psEventId(),
            event_source: 'web',
            send_to_server: true,
            consent_state: window.getConsentState(),
            ecommerce: {
                promotion_id: el.getAttribute('data-dd-promotion-id') || '',
                promotion_name: el.getAttribute('data-dd-promotion-name') || '',
                creative_name: el.getAttribute('data-dd-creative-name') || '',
                creative_slot: el.getAttribute('data-dd-creative-slot') || ''
            }
        };
    }
    var promoNodes = document.querySelectorAll('[data-dd-promotion-id]');
    if (promoNodes.length && 'IntersectionObserver' in window) {
        var promoObserver = new IntersectionObserver(function (entries, obs) {
            entries.forEach(function (entry) {
                if (!entry.isIntersecting) return;
                var el = entry.target;
                var pid = el.getAttribute('data-dd-promotion-id') || '';
                var key = 'view_promotion_' + pid;
                if (window.__ddFiredEvents[key]) { obs.unobserve(el); return; }
                window.__ddFiredEvents[key] = true;
                window.dataLayer.push(ddBuildPromoPayload(el, 'view_promotion'));
                obs.unobserve(el);
            });
        }, { threshold: 0.5 });
        Array.prototype.forEach.call(promoNodes, function (n) { promoObserver.observe(n); });
    }
    document.addEventListener('click', function (ev) {
        var t = ev.target;
        while (t && t !== document) {
            if (t.getAttribute && t.getAttribute('data-dd-promotion-id')) {
                window.dataLayer.push(ddBuildPromoPayload(t, 'select_promotion'));
                break;
            }
            t = t.parentNode;
        }
    });

    // Wishlist add (delegated click). Soporta selectores estandar PrestaShop / modulos populares.
    document.addEventListener('click', function (ev) {
        var target = ev.target;
        while (target && target !== document) {
            if (target.matches && (target.matches('.js-wishlist-button') ||
                target.matches('.wishlist-button-add') ||
                target.matches('[data-wishlist-add]') ||
                target.matches('.btn-add-to-wishlist'))) {
                try {
                    var id = target.getAttribute('data-product-id') || target.getAttribute('data-id-product') || '';
                    var name = target.getAttribute('data-product-name') || '';
                    var price = parseFloat(target.getAttribute('data-product-price')) || 0;
                    var commonW = window.getCommonEventParams();
                    var currency = (typeof currency_iso !== 'undefined') ? currency_iso : 'EUR';
                    window.dataLayer.push({
                        event: 'add_to_wishlist',
                        event_id: window.psEventId(),
                        event_source: commonW.event_source,
                        send_to_server: commonW.send_to_server,
                        consent_state: commonW.consent_state,
                        ecommerce: {
                            currency: currency,
                            value: price,
                            items: [{ item_id: String(id), item_name: name, price: price, quantity: 1 }]
                        }
                    });
                } catch (e) {}
                break;
            }
            target = target.parentNode;
        }
    });

    // Process Standard Conversion Events
    if (typeof gtm_conversion_event !== 'undefined') {
        var common = window.getCommonEventParams();
        // Since getCommonEventParams no longer has event_id, we generate it if missing
        if (!gtm_conversion_event.hasOwnProperty('event_id')) {
            gtm_conversion_event['event_id'] = window.psEventId();
        }
        if (!gtm_conversion_event.hasOwnProperty('user_data') && typeof $dataeh !== 'undefined') {
            if ($dataeh.hasOwnProperty('user_data')) {
                gtm_conversion_event['user_data'] = $dataeh.user_data;
            } else {
                gtm_conversion_event['user_data'] = $dataeh;
            }
        }
        for (var key in common) {
            if (!gtm_conversion_event.hasOwnProperty(key)) {
                gtm_conversion_event[key] = common[key];
            }
        }
        window.dataLayer.push(gtm_conversion_event);
    }

    // Process Adwords Conversion (uses gtag)
    if (typeof gtm_adwords_conversion !== 'undefined') {
        if (typeof gtag === 'function') {
            gtag('event', 'conversion', gtm_adwords_conversion);
        } else {
            // Fallback if gtag is somehow not defined (though core should load it)
            // We reconstruct the push style
            var eventData = Object.assign({ 'event': 'conversion' }, gtm_adwords_conversion);
            // Apply Common Params
            var common = window.getCommonEventParams();
            for (var key in common) {
                if (!eventData.hasOwnProperty(key)) {
                    eventData[key] = common[key];
                }
            }
            window.dataLayer.push(eventData);
        }
    }
}

// Dispara aunque DOMContentLoaded ya haya ocurrido (defer + script en head con DOM ya parseado).
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', ddGtmEventsRun);
} else {
    ddGtmEventsRun();
}
