/* global ofPysOptions */
! function ($, options) {
    // Compatibility layer: Map 'orderflow_facebook' to 'facebook' for backward compatibility
    if (options.hasOwnProperty('orderflow_facebook') && !options.hasOwnProperty('facebook')) {
        options.facebook = options.orderflow_facebook;
    }
    
    if (options.debug) {
        console.log('PYS:', options);
    }
    var uniqueId = {};

    var domain = '';
    if(options.hasOwnProperty("track_cookie_for_subdomains") && options.track_cookie_for_subdomains) {
        domain = getRootDomain(true);
    }

    var Utils = function (options) {

        let isNewSession = checkSession();

        var utmTerms = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];

        var utmId = ['fbadid'];

        function validateEmail(email) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
        }
        function getDomain(url) {

            url = url.replace(/(https?:\/\/)?(www.)?/i, '');

            if (url.indexOf('/') !== -1) {
                return url.split('/')[0];
            }

            return url;
        }
        function loadPixels() {
            if (!options.gdpr.all_disabled_by_api) {
                if (!options.gdpr.facebook_disabled_by_api) {
                    Facebook.loadPixel();
                }
            }
        }

        function checkSession() {
            if( Cookies.get('pys_start_session') === undefined ||
                Cookies.get('pys_session_limit') === undefined) {
                firstVisit = true;
                return true
            }
            return false

        }

        function getTrafficSource() {

            try {

                let referrer = document.referrer.toString(),
                    source;

                let direct = referrer.length === 0;
                let internal = direct ? false : referrer.indexOf(options.siteUrl) === 0;
                let external = !direct && !internal;

                if (external === false) {
                    source = 'direct';
                } else {
                    source = referrer;
                }

                if (source !== 'direct') {
                    // leave only domain (Issue #70)
                    return getDomain(source);
                } else {
                    return source;
                }

            } catch (e) {
                console.error(e);
                return 'direct';
            }

        }

        /**
         * Return query variables object with where property name is query variable
         * and property value is query variable value.
         */
        function getQueryVars() {

            try {

                var result = {},
                    tmp = [];

                window.location.search
                    .substr(1)
                    .split("&")
                    .forEach(function (item) {

                        tmp = item.split('=');

                        if (tmp.length > 1) {
                            result[tmp[0]] = tmp[1];
                        }

                    });

                return result;

            } catch (e) {
                console.error(e);
                return {};
            }

        }


        function getLandingPageValue() {
            let name = "pys_landing_page"
            if(options.visit_data_model === "last_visit") {
                name = "last_pys_landing_page"
            }
            if(Cookies.get(name) && Cookies.get(name) !== "undefined") {
                return Cookies.get(name);
            }
            else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficLanding){
                return options.tracking_analytics.TrafficLanding;
            } else{
                return "";
            }
        }
        function getTrafficSourceValue() {
            let name = "pysTrafficSource"
            if(options.visit_data_model === "last_visit") {
                name = "last_pysTrafficSource"
            }
            if(Cookies.get(name) && Cookies.get(name) !== "undefined") {
                return Cookies.get(name);
            }
            else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficSource){
                return options.tracking_analytics.TrafficSource;
            } else{
                return "";
            }
        }

        function getUTMId(useLast = false) {
            try {
                let cookiePrefix = 'pys_'
                let terms = [];
                if (useLast) {
                    cookiePrefix = 'last_pys_'
                }
                $.each(utmId, function (index, name) {
                    if (Cookies.get(cookiePrefix + name)) {
                        terms[name] = Cookies.get(cookiePrefix + name)
                    }
                    else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficUtmsId[name]) {
                        terms[name] = filterEmails(options.tracking_analytics.TrafficUtmsId[name])
                    }
                });
                return terms;
            } catch (e) {
                console.error(e);
                return [];
            }
        }
        /**
         * Return UTM terms from request query variables or from cookies.
         */
        function getUTMs(useLast = false) {

            try {
                let cookiePrefix = 'pys_'
                if(useLast) {
                    cookiePrefix = 'last_pys_'
                }
                let terms = [];
                $.each(utmTerms, function (index, name) {
                    if (Cookies.get(cookiePrefix + name)) {
                        let value = Cookies.get(cookiePrefix + name);
                        terms[name] = filterEmails(value); // do not allow email in request params (Issue #70)
                    }
                    else if(options.hasOwnProperty("tracking_analytics") && options.tracking_analytics.TrafficUtms[name]) {
                        terms[name] = filterEmails(options.tracking_analytics.TrafficUtms[name])
                    }
                });

                return terms;

            } catch (e) {
                console.error(e);
                return [];
            }

        }

        function getDateTime() {
            var dateTime = new Array();
            var date = new Date(),
                days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
                months = ['January', 'February', 'March', 'April', 'May', 'June',
                    'July', 'August', 'September', 'October', 'November', 'December'
                ],
                hours = ['00-01', '01-02', '02-03', '03-04', '04-05', '05-06', '06-07', '07-08',
                    '08-09', '09-10', '10-11', '11-12', '12-13', '13-14', '14-15', '15-16', '16-17',
                    '17-18', '18-19', '19-20', '20-21', '21-22', '22-23', '23-24'
                ];
            dateTime.push(hours[date.getHours()]);
            dateTime.push(days[date.getDay()]);
            dateTime.push(months[date.getMonth()]);
            return dateTime;
        }

        function filterEmails(value) {
            return validateEmail(value) ? undefined : value;
        }

        /**
         * PUBLIC API
         */
        return {
            PRODUCT_SIMPLE : 0,
            PRODUCT_VARIABLE : 1,
            PRODUCT_BUNDLE : 2,
            PRODUCT_GROUPED : 3,
            utmTerms : utmTerms,
            utmId : utmId,
            fireEventForAllPixel:function(functionName,events){
                if (events.hasOwnProperty(Facebook.tag()))
                    Facebook[functionName](events[Facebook.tag()]);
            },

            // Clone all object members to another and return it
            copyProperties: function (from, to) {
                for (var key in from) {
                    if("function" == typeof from[key]) {
                        continue;
                    }
                    to[key] = from[key];
                }
                return to;
            },

            manageCookies: function () {

                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {
                    if (Cookiebot.consented === false && !Cookiebot.consent['marketing'] && !Cookiebot.consent['statistics']) {
                        return;
                    }
                }
                let cm_consent_not_expressed = false;
                if ( options.gdpr.consent_magic_integration_enabled && window.CS_Data !== undefined && window.CS_Data.cs_refresh_after_consent == 1 ) {
                    if ( Cookies.get( 'cs_viewed_cookie_policy' ) === undefined ) {
                        cm_consent_not_expressed = true;
                    }
                }

                if( !cm_consent_not_expressed && isNewSession && !options.cookie.disabled_all_cookie && !options.cookie.disabled_start_session_cookie) {
                    let duration = options.last_visit_duration * 60000
                    var now = new Date();
                    now.setTime(now.getTime() + duration);
                    Cookies.set('pys_session_limit', true,{ expires: now, path: '/',domain: domain })
                    Cookies.set('pys_start_session', true,{path: '/',domain: domain});
                }

                if (options.ajaxForServerEvent && !Cookies.get('pbid') && Facebook.isEnabled()) {
                    jQuery.ajax({
                        url: options.ajaxUrl,
                        dataType: 'json',
                        data: {
                            action: 'pys_get_pbid'
                        },
                        success: function (res) {
                            if (res.data && res.data.pbid != false && options.send_external_id) {
                                if(!(options.cookie.disabled_all_cookie || options.cookie.externalID_disabled_by_api)){
                                    var expires = parseInt(options.external_id_expire || 180);
                                    Cookies.set('pbid', res.data.pbid, { expires: expires, path: '/',domain: domain });
                                }

                                if(options.hasOwnProperty('facebook')) {
                                    options.facebook.advancedMatching = {
                                        ...options.facebook.advancedMatching,  // spread current advancedMatching values
                                        external_id: res.data.pbid
                                    };
                                }
                            }
                        }
                    });
                } else if (Cookies.get('pbid') && Facebook.isEnabled()){
                    if(Facebook.advancedMatching() && Facebook.advancedMatching().external_id && !(options.cookie.disabled_all_cookie || options.cookie.externalID_disabled_by_api)){
                        let expires = parseInt(options.external_id_expire || 180);
                        Cookies.set('pbid', Facebook.advancedMatching().external_id, { expires: expires, path: '/',domain: domain });
                    }
                }

                let expires = parseInt(options.cookie_duration); //  days
                let queryVars = getQueryVars();
                let landing = window.location.href.split('?')[0];
                try {
                    // save data for first visit
                    if(Cookies.get('pys_first_visit') === undefined && (!options.cookie.disabled_all_cookie)) {

                        if(!options.cookie.disabled_first_visit_cookie)
                        {
                            Cookies.set('pys_first_visit', true, { expires: expires, path: '/',domain: domain });
                        }
                        else {
                            Cookies.remove('pys_first_visit')
                        }

                        if(!options.cookie.disabled_trafficsource_cookie)
                        {
                            Cookies.set('pysTrafficSource', getTrafficSource(), { expires: expires,path: '/',domain: domain });
                        }
                        else {
                            Cookies.remove('pysTrafficSource')
                        }

                        if(!options.cookie.disabled_landing_page_cookie)
                        {
                            Cookies.set('pys_landing_page',landing,{ expires: expires,path: '/',domain: domain });
                        }
                        else {
                            Cookies.remove('pys_landing_page')
                        }

                        if(!options.cookie.disabled_utmTerms_cookie)
                        {
                            $.each(utmTerms, function (index, name) {
                                if (queryVars.hasOwnProperty(name)) {
                                    Cookies.set('pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
                                } else {
                                    Cookies.remove('pys_' + name)
                                }
                            });
                        }
                        else {
                            $.each(utmTerms, function (index, name) {
                                Cookies.remove('pys_' + name)
                            });
                        }

                        if(!options.cookie.disabled_utmId_cookie)
                        {
                            $.each(utmId,function(index,name) {
                                if (queryVars.hasOwnProperty(name)) {
                                    Cookies.set('pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
                                } else {
                                    Cookies.remove('pys_' + name)
                                }
                            })
                        }
                        else {
                            $.each(utmId, function (index, name) {
                                Cookies.remove('pys_' + name)
                            });
                        }
                    }

                    // save data for last visit if it new session
                    if(isNewSession && (!options.cookie.disabled_all_cookie)) {
                        if(!options.cookie.disabled_trafficsource_cookie)
                        {
                            Cookies.set('last_pysTrafficSource', getTrafficSource(), { expires: expires,path: '/',domain: domain });
                        }
                        else {
                            Cookies.remove('last_pysTrafficSource')
                        }

                        if(!options.cookie.disabled_landing_page_cookie)
                        {
                            Cookies.set('last_pys_landing_page',landing,{ expires: expires,path: '/',domain: domain });
                        }
                        else {
                            Cookies.remove('last_pys_landing_page')
                        }

                        if(!options.cookie.disabled_utmTerms_cookie)
                        {
                            $.each(utmTerms, function (index, name) {
                                if (queryVars.hasOwnProperty(name)) {
                                    Cookies.set('last_pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
                                } else {
                                    Cookies.remove('last_pys_' + name)
                                }
                            });
                        }
                        else {
                            $.each(utmTerms, function (index, name) {
                                Cookies.remove('last_pys_' + name)
                            });
                        }

                        if(!options.cookie.disabled_utmId_cookie)
                        {
                            $.each(utmId,function(index,name) {
                                if (queryVars.hasOwnProperty(name)) {
                                    Cookies.set('last_pys_' + name, queryVars[name], { expires: expires,path: '/',domain: domain });
                                } else {
                                    Cookies.remove('last_pys_' + name)
                                }
                            })
                        }
                        else {
                            $.each(utmId, function (index, name) {
                                Cookies.remove('last_pys_' + name)
                            });
                        }

                    }
                    if(options.cookie.disabled_start_session_cookie) {
                        Cookies.remove('pys_start_session')
                        Cookies.remove('pys_session_limit')
                    }
                    if(options.cookie.disabled_all_cookie)
                    {
                        Cookies.remove('pys_first_visit')
                        Cookies.remove('pysTrafficSource')
                        Cookies.remove('pys_landing_page')
                        Cookies.remove('last_pys_landing_page')
                        Cookies.remove('last_pysTrafficSource')
                        Cookies.remove('pys_start_session')
                        Cookies.remove('pys_session_limit')
                        $.each(Utils.utmTerms, function (index, name) {
                            Cookies.remove('pys_' + name)
                        });
                        $.each(Utils.utmId,function(index,name) {
                            Cookies.remove('pys_' + name)
                        })
                        $.each(Utils.utmTerms, function (index, name) {
                            Cookies.remove('last_pys_' + name)
                        });
                        $.each(Utils.utmId,function(index,name) {
                            Cookies.remove('last_pys_' + name)
                        });
                    }
                } catch (e) {
                    console.error(e);
                }
            },
            /**
             * Generate unique ID
             */
            generateUniqueId : function (event) {
                if(event.eventID.length == 0 || (event.type == "static" && options.ajaxForServerStaticEvent) || (event.type !== "static" && options.ajaxForServerEvent)) {
                    let idKey = event.hasOwnProperty('custom_event_post_id') ? event.custom_event_post_id : event.e_id;
                    if (!uniqueId.hasOwnProperty(idKey)) {
                        uniqueId[idKey] = pys_generate_token();
                    }
                    return uniqueId[idKey];
                }
                else if(event.eventID.length !== 0)
                {
                    return event.eventID;
                }
            },

            // Flatten object for sendBeacon compatibility
            flattenObject: function (obj, prefix = '', res = {}) {
                for (const [key, value] of Object.entries(obj)) {
                    const prefixedKey = prefix
                        ? (Array.isArray(obj) ? `${prefix}[${key}]` : `${prefix}[${key}]`)
                        : key;
                    if (value !== null && typeof value === 'object' && !(value instanceof File)) {
                        this.flattenObject(value, prefixedKey, res);
                    } else {
                        res[prefixedKey] = value;
                    }
                }
                return res;
            },

            sendServerAjaxRequest : function(url, data) {
                if (data.action === 'pys_api_event' && data.pixel === 'facebook' && window.ofPysFacebookRest) {

                    // Use Facebook REST API
                    this.sendRestAPIRequest(data, 'facebook');
                    return;
                }

                // Check if sendBeacon is enabled and supported
                if (options.useSendBeacon && navigator.sendBeacon) {
                    try {
                        // Flatten the data object for sendBeacon compatibility
                        const flattenedData = this.flattenObject(data);
                        const formData = new URLSearchParams();

                        // Convert flattened data to URLSearchParams
                        for (const [key, value] of Object.entries(flattenedData)) {
                            if (value !== null && value !== undefined) {
                                formData.append(key, value);
                            }
                        }

                        // Try to send using sendBeacon
                        const success = navigator.sendBeacon(url, formData);
                        if (success) {
                            return; // Successfully sent via sendBeacon
                        }
                    } catch (e) {
                        // If sendBeacon fails, fall back to jQuery.ajax
                        if (options.debug) {
                            console.log('PYS: sendBeacon failed, falling back to jQuery.ajax:', e);
                        }
                    }
                }

                // Fallback to jQuery.ajax
                jQuery.ajax( {
                    type: 'POST',
                    url: url,
                    data: data,
                    headers: {
                        'Cache-Control': 'no-cache'
                    },
                    success: function () {
                    },
                } );
            },

            sendRestAPIRequest: function (data, platform) {
                let restApiUrl;

                // Get platform-specific REST API configuration
                switch (platform) {
                    case 'facebook':
                        restApiUrl = window.ofPysFacebookRest ? window.ofPysFacebookRest.restApiUrl : '/wp-json/of-pys-facebook/v1/event';
                        break;
                    default:
                        console.error('PYS: Unknown platform for REST API:', platform);
                        this.sendAjaxFallback(data);
                        return;
                }

                // Prepare data for REST API (include page_title as top-level for server-side)
                var pageTitle = (data.data && data.data.page_title) || data.page_title || '';
                const restApiData = {
                    event: data.event,
                    data: JSON.stringify(data.data || {}),
                    page_title: pageTitle,
                    ids: JSON.stringify(data.ids || []),
                    eventID: data.event_id || data.eventID || '',
                    woo_order: data.woo_order || '0'
                };

                // Try to send using sendBeacon first (if enabled)
                if (options.useSendBeacon && navigator.sendBeacon) {
                    try {
                        const formData = new URLSearchParams();
                        for (const [key, value] of Object.entries(restApiData)) {
                            formData.append(key, value);
                        }

                        if (navigator.sendBeacon(restApiUrl, formData)) {
                            return;
                        }
                    } catch (e) {
                        // sendBeacon failed, continue to fetch
                    }
                }

                // Try to send using fetch with REST API
                if (window.fetch) {
                    const headers = {
                        'Content-Type': 'application/json'
                    };

                    fetch(restApiUrl, {
                        method: 'POST',
                        headers: headers,
                        body: JSON.stringify(restApiData)
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(platform + ' REST API request failed: ' + response.status);
                            }
                        })
                        .catch(error => {
                            // Fallback to AJAX if REST API fails
                            if (options.debug) {
                                console.log('PYS: ' + platform + ' REST API failed, falling back to AJAX:', error);
                            }
                            this.sendAjaxFallback(data);
                        });
                } else {
                    // Fallback to AJAX if fetch is not supported
                    this.sendAjaxFallback(data);
                }
            },



            // Fallback AJAX method
            sendAjaxFallback: function (data) {
                jQuery.ajax({
                    type: 'POST',
                    url: options.ajaxUrl,
                    data: data,
                    headers: {
                        'Cache-Control': 'no-cache'
                    },
                    success: function () {
                    },
                });
            },
            // clone object
            clone: function(obj) {
                var copy;

                // Handle the 3 simple types, and null or undefined
                if (null == obj || "object" != typeof obj) return obj;

                // Handle Date
                if (obj instanceof Date) {
                    copy = new Date();
                    copy.setTime(obj.getTime());
                    return copy;
                }

                // Handle Array
                if (obj instanceof Array) {
                    copy = [];
                    for (var i = 0, len = obj.length; i < len; i++) {
                        if("function" == typeof obj[i]) {
                            continue;
                        }
                        copy[i] = Utils.clone(obj[i]);
                    }
                    return copy;
                }

                // Handle Object
                if (obj instanceof Object) {
                    copy = {};
                    for (var attr in obj) {
                        if (obj.hasOwnProperty(attr)) {
                            if("function" == typeof obj[attr]) {
                                continue;
                            }
                            copy[attr] = Utils.clone(obj[attr]);
                        }
                    }
                    return copy;
                }

                return obj;
            },

            // Returns array of elements with given tag name
            getTagsAsArray: function (tag) {
                return [].slice.call(document.getElementsByTagName(tag));
            },

            getRequestParams: function () {
                return [];
            },

            /**
             * CUSTOM EVENTS
             */

            setupMouseOverClickEvents: function (eventId, triggers) {

                // Non-default binding used to avoid situations when some code in external js
                // stopping events propagation, eg. returns false, and our handler will never called
                document.addEventListener('mouseover', function(event) {
                    var matchedElements = Array.from(document.querySelectorAll(triggers));
                    var clickedElement = event.target;
                    var closestMatch = clickedElement.closest(triggers);
                    if (matchedElements.includes(clickedElement) || closestMatch){
                        if (event.target.classList.contains('pys-mouse-over-' + eventId)) {
                            return true;
                        } else {
                            event.target.classList.add('pys-mouse-over-' + eventId);
                        }

                        Utils.fireTriggerEvent(eventId);
                    }
                });

            },

            setupCSSClickEvents: function (eventId, triggers) {
                // Non-default binding used to avoid situations when some code in external js
                // stopping events propagation, eg. returns false, and our handler will never called
                document.addEventListener('click', function(event) {
                    let matchedElements = Array.from(document.querySelectorAll(triggers)),
                        clickedElement = event.target,
                        closestMatch = clickedElement.closest(triggers);

                    if (matchedElements.includes(clickedElement) || closestMatch){
                        Utils.fireTriggerEvent(eventId);
                    }
                }, true);
            },

            setupURLClickEvents: function () {

                if( !options.triggerEventTypes.hasOwnProperty('url_click') ) {
                    return;
                }
                // Non-default binding used to avoid situations when some code in external js
                // stopping events propagation, eg. returns false, and our handler will never called
                $('a[data-pys-event-id]').onFirst('click', function (evt) {

                    $(this).attr('data-pys-event-id').split(',').forEach(function (eventId) {

                        eventId = parseInt(eventId);

                        if (isNaN(eventId) === false) {
                            Utils.fireTriggerEvent(eventId);
                        }

                    });

                });


            },

            setupScrollPosEvents: function (eventId, triggers) {

                var scrollPosThresholds = {},
                    docHeight = $(document).height() - $(window).height();

                // convert % to absolute positions
                $.each(triggers, function (index, scrollPos) {

                    // convert % to pixels
                    scrollPos = docHeight * scrollPos / 100;
                    scrollPos = Math.round(scrollPos);

                    scrollPosThresholds[scrollPos] = eventId;

                });

                $(document).on("scroll",function () {

                    var scrollPos = $(window).scrollTop();

                    $.each(scrollPosThresholds, function (threshold, eventId) {

                        // position has not reached yes
                        if (scrollPos <= threshold) {
                            return true;
                        }

                        // fire event only once
                        if (eventId === null) {
                            return true;
                        } else {
                            scrollPosThresholds[threshold] = null;
                        }

                        Utils.fireTriggerEvent(eventId);

                    });

                });


            },

            /**
             * Events
             */

            fireTriggerEvent: function (eventId) {

                if (!options.triggerEvents.hasOwnProperty(eventId)) {
                    return;
                }

                var event = {};
                var events = options.triggerEvents[eventId];

                if (events.hasOwnProperty('facebook')) {
                    event = events.facebook;
                    Facebook.fireEvent(event.name, event);
                }
            },

            fireStaticEvents: function (pixel) {
                // Removed debug log fireStaticEvents() - START. Pixel: ' + pixel);
                // Removed debug log fireStaticEvents() - options.staticEvents:', options.staticEvents);
                
                // Map 'facebook' to 'orderflow_facebook' for compatibility
                var actualPixelKey = pixel;
                if (pixel === 'facebook' && options.staticEvents.hasOwnProperty('orderflow_facebook')) {
                    actualPixelKey = 'orderflow_facebook';
                    // Removed debug log fireStaticEvents() - Mapped "facebook" to "orderflow_facebook"');
                }

                if (options.staticEvents.hasOwnProperty(actualPixelKey)) {
                    // Removed debug log fireStaticEvents() - Found static events for pixel: ' + actualPixelKey);
                    // Removed debug log fireStaticEvents() - Static events data:', options.staticEvents[actualPixelKey]);

                    $.each(options.staticEvents[actualPixelKey], function (eventName, events) {
                        // Removed debug log fireStaticEvents() - Processing event name: ' + eventName + ', Events count: ' + events.length);
                        
                        $.each(events, function (index, eventData) {
                            // Removed debug log fireStaticEvents() - Processing event index: ' + index);
                            // Removed debug log fireStaticEvents() - Event data:', eventData);

                            eventData.fired = eventData.fired || false;

                            if (!eventData.fired) {
                                // Removed debug log fireStaticEvents() - Event not fired yet, proceeding...');

                                var fired = false;

                                // fire event
                                if ('facebook' === pixel) {
                                    // Removed debug log fireStaticEvents() - Calling Facebook.fireEvent()');
                                    // Removed debug log fireStaticEvents() - Event name: ' + eventData.name);
                                    // Removed debug log fireStaticEvents() - Event data params:', eventData.params);
                                    // Removed debug log fireStaticEvents() - Event data payload:', eventData);
                                    
                                    fired = Facebook.fireEvent(eventData.name, eventData);
                                    
                                    // Removed debug log fireStaticEvents() - Facebook.fireEvent() returned: ' + fired);
                                }

                                // prevent event double event firing
                                eventData.fired = fired;
                                // Removed debug log fireStaticEvents() - Set eventData.fired to: ' + fired);
                            } else {
                                // Removed debug log fireStaticEvents() - Event already fired, skipping');
                            }

                        });
                    });

                } else {
                    // Removed debug log fireStaticEvents() - No static events found for pixel: ' + pixel);
                }
                
                // Removed debug log fireStaticEvents() - END');

            },

            /**
             * GDPR
             */

            loadPixels: function () {

                if (options.gdpr.ajax_enabled && !options.gdpr.consent_magic_integration_enabled) {

                    // retrieves actual PYS GDPR filters values which allow to avoid cache issues
                    $.get({
                        url: options.ajaxUrl,
                        dataType: 'json',
                        data: {
                            action: 'pys_get_gdpr_filters_values'
                        },
                        success: function (res) {

                            if (res.success) {

                                options.gdpr.all_disabled_by_api = res.data.all_disabled_by_api;
                                options.gdpr.facebook_disabled_by_api = res.data.facebook_disabled_by_api;

                                options.cookie.externalID_disabled_by_api = res.data.externalID_disabled_by_api;
                                options.cookie.disabled_all_cookie = res.data.disabled_all_cookie;
                                options.cookie.disabled_advanced_form_data_cookie = res.data.disabled_advanced_form_data_cookie;
                                options.cookie.disabled_landing_page_cookie = res.data.disabled_landing_page_cookie;
                                options.cookie.disabled_first_visit_cookie = res.data.disabled_first_visit_cookie;
                                options.cookie.disabled_trafficsource_cookie = res.data.disabled_trafficsource_cookie;
                                options.cookie.disabled_utmTerms_cookie = res.data.disabled_utmTerms_cookie;
                                options.cookie.disabled_utmId_cookie = res.data.disabled_utmId_cookie;
                            }

                            loadPixels();

                        }
                    });

                } else {
                    loadPixels();
                }

            },

            consentGiven: function (pixel) {
                // Only handle Facebook pixel
                if (pixel !== 'facebook') {
                    return true;
                }

                /**
                 * ConsentMagic
                 */
                if ( options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined" ) {

                    let test_prefix = CS_Data.test_prefix;
                    if ( typeof CS_Data.cs_meta_ldu_mode !== "undefined" && CS_Data.cs_meta_ldu_mode && pixel == 'facebook' ) {
                        if ( CS_Data.cs_cache_enabled == 0 || ( CS_Data.cs_cache_enabled == 1 && window.CS_Cache && window.CS_Cache.check_status ) ) {
                            return true;
                        } else {
                            return false;
                        }
                    }

                    if( pixel == 'facebook' && ( CS_Data.cs_script_cat.facebook == 0 || CS_Data.cs_script_cat.facebook == CS_Data.cs_necessary_cat_id ) ) {
                        return true;
                    }

                    let substring = "cs_enabled_cookie_term",
                        theCookies = document.cookie.split( ';' );

                    for ( let i = 1; i <= theCookies.length; i++ ) {
                        if ( theCookies[ i - 1 ].indexOf( substring ) !== -1 ) {
                            let categoryCookie = theCookies[ i - 1 ].replace( 'cs_enabled_cookie_term' + test_prefix + '_', '' );
                            categoryCookie = Number( categoryCookie.replace( /\D+/g, "" ) );
                            let cs_cookie_val = Cookies.get( 'cs_enabled_cookie_term' + test_prefix + '_' + categoryCookie );

                            if ( categoryCookie === CS_Data.cs_script_cat.facebook && pixel == 'facebook' ) {
                                return cs_cookie_val == 'yes';
                            }
                        }
                    }

                    return false;
                }

                /**
                 * Real Cookie Banner
                 */
                if(options.gdpr.real_cookie_banner_integration_enabled) {
                    var consentApi = window.consentApi;
                    if (consentApi) {
                        if (pixel === "facebook") {
                            return consentApi.consentSync("http", "_fbp", "*").cookieOptIn;
                        }
                        return true;
                    }
                }

                /**
                 * Cookiebot
                 */
                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {

                    var cookiebot_consent_category = options.gdpr['cookiebot_' + pixel + '_consent_category'];

                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
                        if (Cookiebot.consented === true || Cookiebot.consent[cookiebot_consent_category]) {
                            return true;
                        }
                    } else {
                        if (Cookiebot.consent[cookiebot_consent_category]) {
                            return true;
                        }
                    }

                    return false;

                }

                /**
                 * Cookie Notice
                 */
                if (options.gdpr.cookie_notice_integration_enabled && typeof cnArgs !== 'undefined') {

                    var cn_cookie = Cookies.get(cnArgs.cookieName);

                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
                        if (typeof cn_cookie === 'undefined' || cn_cookie === 'true') {
                            return true;
                        }
                    } else {
                        if (cn_cookie === 'true') {
                            return true;
                        }
                    }

                    return false;

                }

                /**
                 * Cookie Law Info
                 */
                if (options.gdpr.cookie_law_info_integration_enabled) {
                    var cli_cookie = Cookies.get('cookieyes-consent') ?? Cookies.get('wt_consent') ?? Cookies.get('viewed_cookie_policy');
                    if (options.gdpr[pixel + '_prior_consent_enabled']) {
                        if (typeof cli_cookie === 'undefined') return true;
                        if (
                            cli_cookie &&
                            (cli_cookie === Cookies.get('cookieyes-consent') || cli_cookie === Cookies.get('wt_consent'))
                        ) {
                            if (getCookieYes('analytics') === 'yes') {
                                return true;
                            }
                        } else if (cli_cookie && cli_cookie === Cookies.get('viewed_cookie_policy')) {
                            if (Cookies.get('viewed_cookie_policy') === 'yes') {
                                return true;
                            }
                        }
                    } else {
                        if (
                            cli_cookie &&
                            (cli_cookie === Cookies.get('cookieyes-consent') || cli_cookie === Cookies.get('wt_consent'))
                        ) {
                            if (getCookieYes('analytics') === 'yes') {
                                return true;
                            }
                        } else if (cli_cookie && cli_cookie === Cookies.get('viewed_cookie_policy')) {
                            if (Cookies.get('viewed_cookie_policy') === 'yes') {
                                return true;
                            }
                        }
                    }
                    return false;
                }

                return true;

            },

            setupGdprCallbacks: function () {
                /**
                 * ConsentMagic
                 */
                if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
                    let test_prefix = CS_Data.test_prefix,
                        cs_refresh_after_consent = false,
                        substring = "cs_enabled_cookie_term";

                    if (CS_Data.cs_refresh_after_consent == 1) {
                        cs_refresh_after_consent = CS_Data.cs_refresh_after_consent;
                    }

                    let consent_actions = function () {
                        let theCookies = document.cookie.split( ';' );

                        let consent = {
                            facebook: true,
                        };

                        for (let i = 1 ; i <= theCookies.length; i++) {
                            if (theCookies[i-1].indexOf(substring) !== -1) {
                                let categoryCookie = theCookies[i-1].replace('cs_enabled_cookie_term'+test_prefix+'_','');
                                categoryCookie = Number(categoryCookie.replace(/\D+/g,""));
                                let cs_cookie_val = Cookies.get('cs_enabled_cookie_term'+test_prefix+'_'+categoryCookie);
                                if(cs_cookie_val == 'yes') {
                                    if ( ( categoryCookie === CS_Data.cs_script_cat.facebook ) || ( typeof CS_Data.cs_meta_ldu_mode !== "undefined" && CS_Data.cs_meta_ldu_mode ) ) {
                                        Facebook.loadPixel();
                                    }

                                } else {
                                    if ( ( categoryCookie === CS_Data.cs_script_cat.facebook ) && ( typeof CS_Data.cs_meta_ldu_mode == "undefined" || !CS_Data.cs_meta_ldu_mode ) ) {
                                        Facebook.disable();
                                        consent.facebook = false;
                                    }
                                }
                                if (Cookies.get('cs_enabled_advanced_matching') == 'yes') {
                                    Facebook.loadPixel();
                                }
                            }
                        }
                        Utils.setupGDPRData( consent );
                    }

                    if (!cs_refresh_after_consent) {
                        consent_actions();

                        $(document).on('click','.cs_action_btn',function(e) {
                            e.preventDefault();

                            let consent = {
                                facebook: true,
                            };

                            let elm = $(this),
                                button_action = elm.attr('data-cs_action');

                            if(button_action === 'allow_all') {
                                Facebook.loadPixel();
                                consent.facebook = true;
                                Utils.setupGDPRData( consent );
                            } else if ( button_action === 'disable_all' ) {
                                if ( typeof CS_Data.cs_meta_ldu_mode == "undefined" || CS_Data.cs_meta_ldu_mode == 0 ) {
                                    Facebook.disable();
                                    consent.facebook = false;
                                }
                                Utils.setupGDPRData( consent );
                            } else if ( button_action === 'cs_confirm' ) {
                                consent_actions();
                            }
                        });
                    }
                }
                /**
                 * Real Cookie Banner
                 */
                if(options.gdpr.real_cookie_banner_integration_enabled) {
                    let consentApi = window.consentApi;
                    if (consentApi) {
                        consentApi.consent("http", "_fbp", "*")
                            .then(Facebook.loadPixel.bind(Facebook), Facebook.disable.bind(Facebook));

                        let consent = {
                            facebook: true,
                        };

                        if (!consentApi.consentSync("http", "_fbp", "*").cookieOptIn) {
                            consent.facebook = false;
                        }
                        Utils.setupGDPRData( consent );
                    }
                }
                /**
                 * Cookiebot
                 */
                if (options.gdpr.cookiebot_integration_enabled && typeof Cookiebot !== 'undefined') {

                    window.addEventListener("CookiebotOnConsentReady", function() {

                        let consent = {
                            facebook: true,
                        };

                        Utils.manageCookies();
                        if (Cookiebot.consent.marketing) {
                            Facebook.loadPixel();
                            consent.facebook = true;
                        }
                        if (!Cookiebot.consent.marketing) {
                            Facebook.disable();
                            consent.facebook = false;
                        }

                        Utils.setupGDPRData( consent );
                    });

                }

                /**
                 * Cookie Notice
                 */
                if (options.gdpr.cookie_notice_integration_enabled) {

                    $(document).onFirst('click', '.cn-set-cookie', function () {

                        let consent = {};

                        if ($(this).data('cookie-set') === 'accept') {
                            Facebook.loadPixel();
                            consent = {
                                facebook: true,
                            };
                        } else {
                            Facebook.disable();
                            consent = {
                                facebook: false,
                            };
                        }

                        Utils.setupGDPRData( consent );
                    });

                    $(document).onFirst('click', '.cn-revoke-cookie', function () {
                        Facebook.disable();
                        let consent = {
                            facebook: false,
                        };
                        Utils.setupGDPRData( consent );

                    });

                }

                /**
                 * Cookie Law Info
                 */
                if (options.gdpr.cookie_law_info_integration_enabled) {

                    $(document).onFirst('click', '#wt-cli-accept-all-btn,#cookie_action_close_header, .cky-btn-accept', function () {
                        setTimeout(function (){
                            let cli_cookie = Cookies.get('cookieyes-consent') ?? Cookies.get('wt_consent') ?? Cookies.get('viewed_cookie_policy');
                            if (typeof cli_cookie !== 'undefined') {
                                if (cli_cookie === Cookies.get('cookieyes-consent') || cli_cookie === Cookies.get('wt_consent')) {
                                    if (getCookieYes('analytics') === 'yes') {
                                        Utils.manageCookies();
                                    }
                                } else if (cli_cookie === Cookies.get('viewed_cookie_policy') && cli_cookie == 'yes') {
                                    Utils.manageCookies();
                                }
                            }
                        },1000)
                        Facebook.loadPixel();
                        let consent = {
                            facebook: true,
                        };
                        Utils.setupGDPRData( consent );
                    });

                    $(document).onFirst('click', '#cookie_action_close_header_reject, .cky-btn-reject', function () {
                        Facebook.disable();
                        let consent = {
                            facebook: false,
                        };
                        Utils.setupGDPRData( consent );
                    });

                }

            },

            setupGDPRData: function ( consent ) {
                consent = window.btoa( JSON.stringify( consent ) );
                Cookies.set( 'pys_consent', consent, { expires: 365, path: '/', domain: domain } );
            },

            /**
             * Enrich
             */
            isCheckoutPage: function () {
                return $('body').hasClass('woocommerce-checkout') || document.querySelector('.woocommerce-checkout');
            },
            addCheckoutFields : function() {
                var utm = "";
                var utms = getUTMs()

                $.each(utmTerms, function (index, name) {
                    if(index > 0) {
                        utm+="|";
                    }
                    utm+=name+":"+utms[name];
                });
                var utmIdList = "";
                var utmsIds = getUTMId()
                $.each(utmId, function (index, name) {
                    if(index > 0) {
                        utmIdList+="|";
                    }
                    utmIdList+=name+":"+utmsIds[name];
                });
                var utmIdListLast = "";
                var utmsIdsLast = getUTMId(true)
                $.each(utmId, function (index, name) {
                    if(index > 0) {
                        utmIdListLast+="|";
                    }
                    utmIdListLast+=name+":"+utmsIdsLast[name];
                });


                var utmLast = "";
                var utmsLast = getUTMs(true)
                $.each(utmTerms, function (index, name) {
                    if(index > 0) {
                        utmLast+="|";
                    }
                    utmLast+=name+":"+utmsLast[name];
                });

                var dateTime = getDateTime();
                var landing = getLandingPageValue();
                var lastLanding = getLandingPageValue();
                var trafic = getTrafficSourceValue();
                var lastTrafic = getTrafficSourceValue();

                var $form = $("form.woocommerce-checkout");
                var inputs = {'pys_utm':utm,
                    'pys_utm_id':utmIdList,
                    'pys_browser_time':dateTime.join("|"),
                    'pys_landing':landing,
                    'pys_source':trafic,
                    'pys_order_type': $(".wcf-optin-form").length > 0 ? "wcf-optin" : "normal",

                    'last_pys_landing':lastLanding,
                    'last_pys_source':lastTrafic,
                    'last_pys_utm':utmLast,
                    'last_pys_utm_id':utmIdListLast,
                }

                Object.keys(inputs).forEach(function(key,index) {
                    $form.append("<input type='hidden' name='"+key+"' value='"+inputs[key]+"' /> ");
                });


            },
            getAdvancedFormData: function () {
                let dataStr = Cookies.get("of_pys_advanced_form_data");
                if(dataStr === undefined) {
                    return {'first_name':"",'last_name':"",'email':"",'phone':""};
                } else {
                    return JSON.parse(dataStr);
                }
            },
            getDateTime: getDateTime,
            getTrafficSourceValue: getTrafficSourceValue,
            getLandingPageValue: getLandingPageValue
        };

    }(options);

    var Facebook = function (options) {


        var defaultEventTypes = [
            'PageView',
            'ViewContent',
            'Search',
            'AddToCart',
            'AddToWishlist',
            'InitiateCheckout',
            'AddPaymentInfo',
            'Purchase',
            'Lead',

            'Subscribe',
            'CustomizeProduct',
            'FindLocation',
            'StartTrial',
            'SubmitApplication',
            'Schedule',
            'Contact',
            'Donate'
        ];

        var initialized = false;
        var genereateFbp = function (){
            return !Cookies.get('_fbp') ? 'fb.1.'+Date.now()+'.'+Math.floor(1000000000 + Math.random() * 9000000000) : Cookies.get('_fbp');
        };
        var genereateFbc = function (){
            return getUrlParameter('fbclid') ? 'fb.1.'+Date.now()+'.'+getUrlParameter('fbclid') : ''
        };
        // fire server side event gdpr plugin installed
        var isApiDisabled = options.gdpr.all_disabled_by_api ||
            options.gdpr.facebook_disabled_by_api ||
            options.gdpr.cookiebot_integration_enabled ||
            options.gdpr.consent_magic_integration_enabled ||
            options.gdpr.cookie_notice_integration_enabled ||
            options.gdpr.cookie_law_info_integration_enabled;

        /**
         *
         * @param allData
         * @param params
         * @returns {string | null}
         */
        function sendFbServerEvent(allData,name,params) {
            let eventId = null;
            if(options.facebook.serverApiEnabled) {

                if(allData.e_id === "woo_remove_from_cart") {// server event will sended from hook
                    Facebook.updateEventId(allData.name);
                    allData.eventID = Facebook.getEventId(allData.name);
                } else {
                    // send event from server if they was bloc by gdpr or need send with delay
                    allData.eventID = Utils.generateUniqueId(allData);

                    // Ensure post_id is present for server-side events
                    if (!params.hasOwnProperty('post_id') || !params['post_id']) {
                        // Try to get from allData.params
                        if (allData && allData.params && allData.params.post_id) {
                            params['post_id'] = allData.params.post_id;
                        }
                        // Try to get from content_ids
                        if ((!params['post_id']) && params['content_ids']) {
                            var contentId = params['content_ids'];
                            if (Array.isArray(contentId) && contentId.length > 0) {
                                params['post_id'] = contentId[0];
                            } else if (contentId) {
                                params['post_id'] = contentId;
                            }
                        }
                        // Try to get from URL
                        if (!params['post_id']) {
                            var currentUrl = window.location.href;
                            var urlMatch = currentUrl.match(/\/post\/(\d+)/) || 
                                           currentUrl.match(/\/p\/(\d+)/) || 
                                           currentUrl.match(/[?&]p=(\d+)/) || 
                                           currentUrl.match(/\/product\/(\d+)/);
                            if (urlMatch && urlMatch[1]) {
                                params['post_id'] = urlMatch[1];
                            }
                        }
                    }
                    
                    // Ensure page_title is present for server-side events (from PHP getStandardParams)
                    if (!params.hasOwnProperty('page_title') || !params['page_title']) {
                        if (options && options.current_page_title) {
                            params['page_title'] = options.current_page_title;
                        } else if (document.title) {
                            params['page_title'] = document.title;
                        }
                    }

                    if(Cookies.get('_fbp')){
                        params._fbp = Cookies.get('_fbp');
                    }
                    if(Cookies.get('_fbc')){
                        params._fbc = Cookies.get('_fbc');
                    }

                    if( options.ajaxForServerEvent || isApiDisabled ){

                        var pageTitle = params['page_title'] || (options && options.current_page_title) || document.title || '';
                        var json = {
                            action: 'pys_api_event',
                            pixel: 'facebook',
                            event: name,
                            data: params,
                            page_title: pageTitle,
                            ids: options.facebook.pixelIds,
                            eventID: allData.eventID,
                            url: window.location.href,
                            ajax_event: options.ajax_event
                        };
                        if(allData.hasOwnProperty('woo_order')) {
                            json['woo_order'] = allData.woo_order;
                        }

                        if (allData.e_id === "automatic_event_internal_link" || allData.e_id === "automatic_event_outbound_link") {
                            setTimeout(() => Utils.sendServerAjaxRequest(options.ajaxUrl, json), 500);
                        } else if (allData.type != 'static') {
                            Utils.sendServerAjaxRequest(options.ajaxUrl, json);
                        }

                        if ( ( allData.type == 'static' && options.ajaxForServerStaticEvent ) || ( allData.hasOwnProperty( 'ajaxFire' ) && allData.ajaxFire ) ) {
                            Utils.sendServerAjaxRequest( options.ajaxUrl, json );
                        }
                    }
                }
                delete params._fbp;
                delete params._fbc;
                eventId = allData.eventID
            }
            return eventId;
        }

        function fireEvent(name, allData) {
            console.log('[PYS Tags Debug] fireEvent called:', name);
            if(typeof window.pys_event_data_filter === "function" && window.pys_disable_event_filter(name,'facebook')) {
                return;
            }

            var actionType = defaultEventTypes.includes(name) ? 'track' : 'trackCustom';
            
            var data = allData.params;
            var params = {};
            var arg = {};
            Utils.copyProperties(data, params);
            
            // Add time-based parameters (event_day, event_hour, event_month)
            var dateTime = Utils.getDateTime();
            if (!params.hasOwnProperty('event_day')) {
                params['event_day'] = dateTime[1]; // day name
            }
            if (!params.hasOwnProperty('event_hour')) {
                params['event_hour'] = dateTime[0]; // hour range
            }
            if (!params.hasOwnProperty('event_month')) {
                params['event_month'] = dateTime[2]; // month name
            }
            
            // Add traffic_source
            if (!params.hasOwnProperty('traffic_source')) {
                var trafficSource = Utils.getTrafficSourceValue();
                if (trafficSource) {
                    params['traffic_source'] = trafficSource;
                }
            }
            
            // Add landing_page
            if (!params.hasOwnProperty('landing_page')) {
                var landingPage = Utils.getLandingPageValue();
                if (landingPage) {
                    params['landing_page'] = landingPage;
                }
            }
            
            // page_title is now added by PHP getStandardParams (injected into PageView init_event params)
            
            // Add currency if not present (for WooCommerce/EDD pages) - always uppercase
            if (!params.hasOwnProperty('currency') || !params['currency']) {
                var currencyValue = null;
                // Try to get from WooCommerce
                if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.currency) {
                    currencyValue = wc_add_to_cart_params.currency;
                } else if (typeof woocommerce_params !== 'undefined' && woocommerce_params.currency) {
                    currencyValue = woocommerce_params.currency;
                } else if (window.ofPysWooProductData) {
                    // Try to get from product data
                    var productId = params['post_id'] || params['content_ids'];
                    if (productId) {
                        if (Array.isArray(productId)) {
                            productId = productId[0];
                        }
                        if (window.ofPysWooProductData[productId]) {
                            var productData = window.ofPysWooProductData[productId].facebook || window.ofPysWooProductData[productId].orderflow_facebook;
                            if (productData && productData.params && productData.params.currency) {
                                currencyValue = productData.params.currency;
                            }
                        }
                    }
                }
                if (currencyValue) {
                    params['currency'] = currencyValue.toUpperCase();
                }
            } else if (params['currency']) {
                // Ensure existing currency is uppercase
                params['currency'] = params['currency'].toUpperCase();
            }
            
            // Add post_id if not present
            // For PageView events, prioritize URL and body class detection since content_ids may not be available
            if (!params.hasOwnProperty('post_id') || !params['post_id']) {
                // First, try to get from PHP (ofPysOptions.current_post_id) - most reliable
                if (options && options.current_post_id) {
                    params['post_id'] = options.current_post_id;
                }
                // Then try to get from allData.params
                if ((!params['post_id']) && allData && allData.params && allData.params.post_id) {
                    params['post_id'] = allData.params.post_id;
                }
                
                // For PageView events, try URL and body class first (before product data)
                if (name === 'PageView' && !params['post_id']) {
                    // Try to get from URL (current page URL) - most reliable for PageView
                    var currentUrl = window.location.href;
                    var urlMatch = currentUrl.match(/\/post\/(\d+)/) || 
                                   currentUrl.match(/\/p\/(\d+)/) || 
                                   currentUrl.match(/[?&]p=(\d+)/) || 
                                   currentUrl.match(/\/product\/(\d+)/) ||
                                   currentUrl.match(/\/product\/([^\/]+)/) ||
                                   currentUrl.match(/\/\?p=(\d+)/) ||
                                   currentUrl.match(/\/page\/(\d+)/);
                    if (urlMatch && urlMatch[1]) {
                        params['post_id'] = urlMatch[1];
                    }
                    
                    // Try to get from body class or data attribute
                    if (!params['post_id']) {
                        var body = document.body;
                        if (body) {
                            var postIdMatch = body.className.match(/postid-(\d+)/) || 
                                             body.className.match(/product-(\d+)/) ||
                                             body.className.match(/page-id-(\d+)/) ||
                                             body.className.match(/single-(\d+)/);
                            if (postIdMatch && postIdMatch[1]) {
                                params['post_id'] = postIdMatch[1];
                            } else if (body.getAttribute && body.getAttribute('data-post-id')) {
                                params['post_id'] = body.getAttribute('data-post-id');
                            } else if (body.getAttribute && body.getAttribute('data-product-id')) {
                                params['post_id'] = body.getAttribute('data-product-id');
                            }
                        }
                    }
                    
                    // Try to get from meta tag
                    if (!params['post_id']) {
                        var postIdMeta = document.querySelector('meta[property="og:url"]') || 
                                         document.querySelector('meta[name="post_id"]') ||
                                         document.querySelector('meta[property="article:id"]') ||
                                         document.querySelector('meta[name="article:id"]');
                        if (postIdMeta) {
                            var url = postIdMeta.getAttribute('content') || postIdMeta.getAttribute('value');
                            if (url) {
                                var match = url.match(/\/post\/(\d+)/) || 
                                           url.match(/\/p\/(\d+)/) || 
                                           url.match(/[?&]p=(\d+)/) || 
                                           url.match(/\/product\/(\d+)/) ||
                                           url.match(/\/product\/([^\/]+)/);
                                if (match && match[1]) {
                                    params['post_id'] = match[1];
                                }
                            }
                        }
                    }
                    
                    // Try to get from WooCommerce global variables
                    if (!params['post_id']) {
                        if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.product_id) {
                            params['post_id'] = wc_add_to_cart_params.product_id;
                        } else if (typeof woocommerce_params !== 'undefined' && woocommerce_params.product_id) {
                            params['post_id'] = woocommerce_params.product_id;
                        }
                    }
                }
                
                // For non-PageView events, try product data first
                if (name !== 'PageView' && (!params['post_id']) && window.ofPysWooProductData) {
                    var productId = params['content_ids'] || (allData && allData.params && allData.params.content_ids);
                    if (productId) {
                        if (Array.isArray(productId)) {
                            productId = productId[0];
                        }
                        if (window.ofPysWooProductData[productId]) {
                            var productData = window.ofPysWooProductData[productId].facebook || window.ofPysWooProductData[productId].orderflow_facebook;
                            if (productData && productData.params && productData.params.post_id) {
                                params['post_id'] = productData.params.post_id;
                            } else if (productId) {
                                // Use productId itself as post_id if available
                                params['post_id'] = productId;
                            }
                        } else if (productId) {
                            // Use productId as post_id even if not in ofPysWooProductData
                            params['post_id'] = productId;
                        }
                    }
                }
                
                // For non-PageView events, try URL if product data didn't work
                if (name !== 'PageView' && !params['post_id']) {
                    var currentUrl = window.location.href;
                    var urlMatch = currentUrl.match(/\/post\/(\d+)/) || 
                                   currentUrl.match(/\/p\/(\d+)/) || 
                                   currentUrl.match(/[?&]p=(\d+)/) || 
                                   currentUrl.match(/\/product\/(\d+)/) ||
                                   currentUrl.match(/\/product\/([^\/]+)/) ||
                                   currentUrl.match(/\/\?p=(\d+)/) ||
                                   currentUrl.match(/\/page\/(\d+)/);
                    if (urlMatch && urlMatch[1]) {
                        params['post_id'] = urlMatch[1];
                    }
                }
                
                // Try to get from meta tag (for non-PageView events that didn't get it yet)
                if (name !== 'PageView' && !params['post_id']) {
                    var postIdMeta = document.querySelector('meta[property="og:url"]') || 
                                     document.querySelector('meta[name="post_id"]') ||
                                     document.querySelector('meta[property="article:published_time"]') ||
                                     document.querySelector('meta[name="article:published_time"]');
                    if (postIdMeta) {
                        var url = postIdMeta.getAttribute('content') || postIdMeta.getAttribute('value');
                        if (url) {
                            var match = url.match(/\/post\/(\d+)/) || 
                                       url.match(/\/p\/(\d+)/) || 
                                       url.match(/[?&]p=(\d+)/) || 
                                       url.match(/\/product\/(\d+)/) ||
                                       url.match(/\/product\/([^\/]+)/);
                            if (match && match[1]) {
                                params['post_id'] = match[1];
                            }
                        }
                    }
                }
                
                // Try to get from body class or data attribute (for non-PageView events)
                if (name !== 'PageView' && !params['post_id']) {
                    var body = document.body;
                    if (body) {
                        var postIdMatch = body.className.match(/postid-(\d+)/) || 
                                         body.className.match(/product-(\d+)/) ||
                                         body.className.match(/page-id-(\d+)/) ||
                                         body.className.match(/single-(\d+)/);
                        if (postIdMatch && postIdMatch[1]) {
                            params['post_id'] = postIdMatch[1];
                        } else if (body.getAttribute && body.getAttribute('data-post-id')) {
                            params['post_id'] = body.getAttribute('data-post-id');
                        } else if (body.getAttribute && body.getAttribute('data-product-id')) {
                            params['post_id'] = body.getAttribute('data-product-id');
                        }
                    }
                }
                
                // Try to get from WooCommerce global variables (for non-PageView events)
                if (name !== 'PageView' && !params['post_id']) {
                    if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.product_id) {
                        params['post_id'] = wc_add_to_cart_params.product_id;
                    } else if (typeof woocommerce_params !== 'undefined' && woocommerce_params.product_id) {
                        params['post_id'] = woocommerce_params.product_id;
                    }
                }
            }
            
            // Add post_type if not present
            if (!params.hasOwnProperty('post_type') || !params['post_type']) {
                var body = document.body;
                if (body) {
                    var className = body.className || '';
                    // Avoid matching page-template-default as "template-default"
                    var postTypeMatch = className.match(/(?:^|\s)single-([a-z0-9_-]+)(?:\s|$)/) || className.match(/(?:^|\s)post-type-archive-([a-z0-9_-]+)(?:\s|$)/);
                    if (postTypeMatch && postTypeMatch[1]) {
                        params['post_type'] = postTypeMatch[1];
                    } else if (className.indexOf('single-product') !== -1 || className.indexOf('woocommerce') !== -1) {
                        params['post_type'] = 'product';
                    } else if (className.indexOf('single-post') !== -1) {
                        params['post_type'] = 'post';
                    } else if (className.indexOf('woocommerce-checkout') !== -1 || className.indexOf('page-id-') !== -1 || className.indexOf('page-template') !== -1 || /(?:^|\s)page(?:\s|$)/.test(className)) {
                        params['post_type'] = 'page';
                    }
                }
            }
            
            // Add tags if not present (always add for product PageView, blank if no tags)
            console.log('[PYS Tags Debug] before tags block - name:', name, 'post_type:', params['post_type'], 'params.tags:', params['tags'], 'hasOwnProperty tags:', params.hasOwnProperty('tags'));
            console.log('[PYS Tags Debug] options.current_tags:', JSON.stringify(options ? options.current_tags : 'no options'), 'options.hasOwnProperty(current_tags):', options ? options.hasOwnProperty('current_tags') : false);
            if (name === 'PageView' && params['post_type'] === 'product') {
                params['tags'] = (options && options.hasOwnProperty('current_tags')) ? (options.current_tags || '') : '';
                console.log('[PYS Tags Debug] PageView product block - set params.tags from options:', params['tags']);
                if (params['tags'] === '' && window.ofPysWooProductData && params['post_id']) {
                    var _pid = Array.isArray(params['post_id']) ? params['post_id'][0] : params['post_id'];
                    var _p = window.ofPysWooProductData[_pid];
                    var _srcLog = _p ? (_p.orderflow_facebook || _p.facebook) : null;
                    console.log('[PYS Tags Debug] PageView - ofPysWooProductData[' + _pid + '].params:', _srcLog && _srcLog.params ? _srcLog.params : 'no params');
                    console.log('[PYS Tags Debug] PageView - ofPysWooProductData[' + _pid + '].params.tags:', _srcLog && _srcLog.params ? _srcLog.params.tags : 'N/A');
                    if (_p && (_p.orderflow_facebook || _p.facebook)) {
                        var _src = _p.orderflow_facebook || _p.facebook;
                        if (_src.params && _src.params.tags) {
                            params['tags'] = _src.params.tags;
                            console.log('[PYS Tags Debug] PageView - got tags from ofPysWooProductData:', params['tags']);
                        }
                    }
                }
            }
            if (!params.hasOwnProperty('tags')) {
                if (options && options.hasOwnProperty('current_tags')) {
                    params['tags'] = options.current_tags || '';
                }
                // Try to get product tags from meta or data attributes
                if (!params['tags']) {
                    var tagsMeta = document.querySelector('meta[property="product:tag"]') || document.querySelector('meta[name="tags"]');
                    if (tagsMeta) {
                        var tagsContent = tagsMeta.getAttribute('content') || tagsMeta.getAttribute('value');
                        if (tagsContent) {
                            params['tags'] = tagsContent;
                        }
                    }
                }
                // Try to get from WooCommerce product data
                if (!params['tags'] && window.ofPysWooProductData) {
                    var productId = params['post_id'] || params['content_ids'];
                    if (productId) {
                        // Handle array of content_ids
                        if (Array.isArray(productId)) {
                            productId = productId[0];
                        }
                        if (window.ofPysWooProductData[productId] && window.ofPysWooProductData[productId].facebook && window.ofPysWooProductData[productId].facebook.params && window.ofPysWooProductData[productId].facebook.params.tags) {
                            params['tags'] = window.ofPysWooProductData[productId].facebook.params.tags;
                        } else if (window.ofPysWooProductData[productId] && window.ofPysWooProductData[productId].orderflow_facebook && window.ofPysWooProductData[productId].orderflow_facebook.params && window.ofPysWooProductData[productId].orderflow_facebook.params.tags) {
                            params['tags'] = window.ofPysWooProductData[productId].orderflow_facebook.params.tags;
                        }
                    }
                }
            }
            console.log('[PYS Tags Debug] after tags block - params.tags:', params['tags'], 'hasOwnProperty tags:', params.hasOwnProperty('tags'));
            
            // For ViewContent events, ensure content_name is present (product name)
            if (name === 'ViewContent' && (!params.hasOwnProperty('content_name') || !params['content_name'])) {
                var vcProductId = params['post_id'] || (params['content_ids'] && (Array.isArray(params['content_ids']) ? params['content_ids'][0] : params['content_ids']));
                if (vcProductId && window.ofPysWooProductData && window.ofPysWooProductData[vcProductId]) {
                    var vcProductData = window.ofPysWooProductData[vcProductId].orderflow_facebook || window.ofPysWooProductData[vcProductId].facebook;
                    if (vcProductData && vcProductData.params && vcProductData.params.content_name) {
                        params['content_name'] = vcProductData.params.content_name;
                    }
                }
                if (!params['content_name'] && (options && options.current_page_title)) {
                    params['content_name'] = options.current_page_title;
                }
                if (!params['content_name'] && document.title) {
                    params['content_name'] = document.title;
                }
            }
            
            // For Purchase events, ensure content_name, coupon_used, total are present
            if (name === 'Purchase') {
                if (!params.hasOwnProperty('content_name') || !params['content_name']) {
                    if (options && options.current_page_title) {
                        params['content_name'] = options.current_page_title;
                    } else if (document.title) {
                        params['content_name'] = document.title;
                    }
                }
                if (!params.hasOwnProperty('coupon_used')) {
                    params['coupon_used'] = 'no';
                }
                if (!params.hasOwnProperty('total') && params.hasOwnProperty('value')) {
                    params['total'] = params['value'];
                }
            }
            
            // For AddToCart events, ensure all required parameters are present
            if (name === 'AddToCart') {
                // Get product ID from params or allData
                var productId = params['post_id'] || (params['content_ids'] && Array.isArray(params['content_ids']) && params['content_ids'].length > 0 ? params['content_ids'][0] : (params['content_ids'] ? params['content_ids'] : null));
                
                // If productId is still not found, try to get from allData
                if (!productId && allData && allData.params) {
                    productId = allData.params.post_id || (allData.params.content_ids && Array.isArray(allData.params.content_ids) && allData.params.content_ids.length > 0 ? allData.params.content_ids[0] : (allData.params.content_ids ? allData.params.content_ids : null));
                }
                
                // Try to get missing parameters from product data
                if (productId && window.ofPysWooProductData && window.ofPysWooProductData[productId]) {
                    var productData = window.ofPysWooProductData[productId].orderflow_facebook || window.ofPysWooProductData[productId].facebook;
                    
                    if (productData && productData.params) {
                        // Copy all missing params from product data
                        if (!params.hasOwnProperty('category_name') || !params['category_name']) {
                            if (productData.params.category_name) {
                                params['category_name'] = productData.params.category_name;
                            }
                        }
                        
                        if (!params.hasOwnProperty('content_ids') || !params['content_ids'] || (Array.isArray(params['content_ids']) && params['content_ids'].length === 0)) {
                            if (productData.params.content_ids) {
                                params['content_ids'] = productData.params.content_ids;
                            }
                        }
                        
                        if (!params.hasOwnProperty('content_name') || !params['content_name']) {
                            if (productData.params.content_name) {
                                params['content_name'] = productData.params.content_name;
                            }
                        }
                        
                        if (!params.hasOwnProperty('content_type') || !params['content_type']) {
                            if (productData.params.content_type) {
                                params['content_type'] = productData.params.content_type;
                            } else {
                                params['content_type'] = 'product';
                            }
                        }
                        
                        if (!params.hasOwnProperty('contents') || !params['contents'] || (Array.isArray(params['contents']) && params['contents'].length === 0)) {
                            if (productData.params.contents) {
                                params['contents'] = productData.params.contents;
                            }
                        }
                        
                        if (!params.hasOwnProperty('value') || !params['value']) {
                            if (productData.params.value) {
                                params['value'] = productData.params.value;
                            }
                        }
                        
                        if (!params.hasOwnProperty('currency') || !params['currency']) {
                            if (productData.params.currency) {
                                params['currency'] = productData.params.currency.toUpperCase();
                            }
                        }
                        
                        // Ensure value is present (fallback to product price if not available)
                        if (!params.hasOwnProperty('value') || !params['value'] || params['value'] === 0) {
                            // Try to get from WooCommerce product data if available
                            if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.product_price) {
                                params['value'] = parseFloat(wc_add_to_cart_params.product_price);
                            }
                        }
                    }
                }
                
                // Ensure content_name is present for AddToCart (fallback if not from product data)
                if (!params.hasOwnProperty('content_name') || !params['content_name']) {
                    if (options && options.current_page_title) {
                        params['content_name'] = options.current_page_title;
                    } else if (document.title) {
                        params['content_name'] = document.title;
                    }
                }
                
                // Ensure event_url is present
                if (!params.hasOwnProperty('event_url') || !params['event_url']) {
                    params['event_url'] = window.location.href;
                }
                
                // Ensure plugin is present
                if (!params.hasOwnProperty('plugin') || !params['plugin']) {
                    params['plugin'] = 'OrderFlow';
                }
                
                // Ensure user_role is present (try to get from cookie or set default)
                if (!params.hasOwnProperty('user_role') || !params['user_role']) {
                    // Try to get from cookie if available
                    var userRoleCookie = Cookies.get('pys_user_role') || Cookies.get('of_pys_user_role');
                    if (userRoleCookie) {
                        params['user_role'] = userRoleCookie;
                    } else {
                        // Default to guest if not logged in
                        params['user_role'] = 'guest';
                    }
                }
                
                // Ensure currency is present (fallback) - like PageView does
                if (!params.hasOwnProperty('currency') || !params['currency']) {
                    // Try to get from WooCommerce (like PageView does)
                    if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.currency) {
                        params['currency'] = wc_add_to_cart_params.currency.toUpperCase();
                    } else if (typeof woocommerce_params !== 'undefined' && woocommerce_params.currency) {
                        params['currency'] = woocommerce_params.currency.toUpperCase();
                    } else if (typeof get_woocommerce_currency === 'function') {
                        // Try to get from WooCommerce function if available
                        try {
                            var wcCurrency = get_woocommerce_currency();
                            if (wcCurrency) {
                                params['currency'] = wcCurrency.toUpperCase();
                            }
                        } catch(e) {
                            // Ignore error
                        }
                    }
                }
            }
            
            // Removed debug log fireEvent() - Params after copy:', params);

            let eventId = sendFbServerEvent(allData,name,params)
            // Removed debug log fireEvent() - Server event ID: ' + (eventId || 'null'));


            if("hCR" === name) {
                // Removed debug log fireEvent() - EXITING: hCR event');
                return;
            }

            if (options.debug) {
                console.log('[Facebook] ' + name, params,"eventID",eventId);
            }

            if(eventId != null) {
                arg.eventID = eventId;
                // Removed debug log fireEvent() - Added eventID to arg: ' + eventId);
            }

            // Removed debug log fireEvent() - Calling fbq() with:');
            // Removed debug log fireEvent() - actionType:', actionType);
            // Removed debug log fireEvent() - name:', name);
            // Removed debug log fireEvent() - params:', params);
            // Removed debug log fireEvent() - arg:', arg);
            
            console.log('[PYS Tags Debug] FINAL before fbq - name:', name, 'params.tags:', params['tags'], 'params keys:', Object.keys(params));
            fbq(actionType, name, params, arg);
            
            // Removed debug log fireEvent() - END. fbq() called');

        }

        /**
         * Public API
         */
        return {
            tag: function() {
                return "facebook";
            },
            isEnabled: function () {
                // Check for both 'facebook' and 'orderflow_facebook' keys for compatibility
                return options.hasOwnProperty('facebook') || options.hasOwnProperty('orderflow_facebook');
            },

            disable: function () {
                initialized = false;
            },
            advancedMatching: function () {
                if(options.facebook.advancedMatchingEnabled) {
                    let advancedMatchingForm = Utils.getAdvancedFormData();
                    let advancedMatching = {};
                    if(Object.keys(options.facebook.advancedMatching).length > 0) {
                        advancedMatching = options.facebook.advancedMatching;
                    }

                    if(!advancedMatching.hasOwnProperty("em")
                        && advancedMatchingForm.hasOwnProperty("email") && advancedMatchingForm["email"].length > 0) {
                        advancedMatching["em"] = advancedMatchingForm["email"];
                    }
                    if(!advancedMatching.hasOwnProperty("ph")
                        && advancedMatchingForm.hasOwnProperty("phone") && advancedMatchingForm["phone"].length > 0) {
                        advancedMatching["ph"] = advancedMatchingForm["phone"];
                    }
                    if(!advancedMatching.hasOwnProperty("fn")
                        && advancedMatchingForm.hasOwnProperty("first_name") && advancedMatchingForm["first_name"].length > 0) {
                        advancedMatching["fn"] = advancedMatchingForm["first_name"];
                    }
                    if(!advancedMatching.hasOwnProperty("ln")
                        && advancedMatchingForm.hasOwnProperty("last_name") && advancedMatchingForm["last_name"].length > 0) {
                        advancedMatching["ln"] = advancedMatchingForm["last_name"];
                    }
                    if(!advancedMatching.hasOwnProperty("external_id")){
                        if (Cookies.get('pbid') || (options.hasOwnProperty('pbid') && options.pbid)) {
                            advancedMatching["external_id"] = Cookies.get('pbid') ? Cookies.get('pbid') : options.pbid;
                        }
                    }
                    else if(advancedMatching.external_id != Cookies.get('pbid'))
                    {
                        advancedMatching["external_id"] = Cookies.get('pbid') ? Cookies.get('pbid') : advancedMatching.external_id;
                    }
                    if(Object.keys(advancedMatching).length > 0) {
                        return advancedMatching;
                    }
                }
                return false
            },
            /**
             * Load pixel's JS
             */
            loadPixel: function () {
                // Removed debug log loadPixel() - START');
                // Removed debug log loadPixel() - Initialized: ' + initialized);
                // Removed debug log loadPixel() - Is enabled: ' + this.isEnabled());
                // Removed debug log loadPixel() - Consent given: ' + Utils.consentGiven('facebook'));
                
                if (initialized || !this.isEnabled() || !Utils.consentGiven('facebook')) {
                    // Removed debug log loadPixel() - EXITING: Already initialized, not enabled, or consent not given');
                    return;
                }

                // Removed debug log loadPixel() - Loading Facebook pixel script');
                !function (f, b, e, v, n, t, s) {
                    if (f.fbq) {
                        // Removed debug log loadPixel() - fbq already exists, skipping script load');
                        return;
                    }
                    n = f.fbq = function () {
                        n.callMethod ?
                            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
                    };
                    if (!f._fbq) f._fbq = n;
                    n.push = n;
                    n.loaded = !0;
                    n.version = '2.0';
                    n.agent = 'dvorderflow';
                    n.queue = [];
                    t = b.createElement(e);
                    t.async = !0;
                    t.src = v;
                    s = b.getElementsByTagName(e)[0];
                    s.parentNode.insertBefore(t, s)
                    // Removed debug log loadPixel() - Facebook pixel script inserted');
                }(window,
                    document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');

                let expires = parseInt(options.cookie_duration);
                if(!Cookies.get('_fbp')) {
                    Cookies.set('_fbp',genereateFbp(),  { expires: expires,path: '/',domain: domain });
                    // Removed debug log loadPixel() - Set _fbp cookie');
                }

                if(getUrlParameter('fbclid')) {
                    Cookies.set('_fbc',genereateFbc(),  { expires: expires,path: '/',domain: domain });
                    // Removed debug log loadPixel() - Set _fbc cookie');
                }
                
                // Removed debug log loadPixel() - Pixel IDs:', options.facebook.pixelIds);
                // initialize pixel
                options.facebook.pixelIds.forEach(function (pixelId) {
                    // Removed debug log loadPixel() - Initializing pixel ID: ' + pixelId);
                    
                    if (options.facebook.removeMetadata) {
                        fbq('set', 'autoConfig', false, pixelId);
                        // Removed debug log loadPixel() - Set autoConfig to false for pixel: ' + pixelId);
                    }
                    let advancedMatching = Facebook.advancedMatching();
                    // Removed debug log loadPixel() - Advanced matching:', advancedMatching);

                    if ( +options.facebook.meta_ldu === 1  ) {
                        fbq( 'dataProcessingOptions', [ 'LDU' ], 0, 0 );
                        // Removed debug log loadPixel() - Set LDU mode');
                    }

                    if (options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined") {
                        if(!advancedMatching) {
                            fbq('init', pixelId);
                            // Removed debug log loadPixel() - Called fbq(init) without advanced matching');
                        } else {
                            var test_prefix = CS_Data.test_prefix;
                            var cs_advanced_matching = Cookies.get('cs_enabled_advanced_matching'+test_prefix);
                            if (jQuery('#cs_enabled_advanced_matching'+test_prefix).length > 0) {
                                if (cs_advanced_matching == 'yes') {
                                    fbq('init', pixelId, advancedMatching);
                                    // Removed debug log loadPixel() - Called fbq(init) with advanced matching (consent magic)');
                                } else {
                                    fbq('init', pixelId);
                                    // Removed debug log loadPixel() - Called fbq(init) without advanced matching (consent magic)');
                                }
                            } else {
                                fbq('init', pixelId, advancedMatching);
                                // Removed debug log loadPixel() - Called fbq(init) with advanced matching (consent magic fallback)');
                            }
                        }
                    } else {
                        if(!advancedMatching) {
                            fbq('init', pixelId);
                            // Removed debug log loadPixel() - Called fbq(init) without advanced matching');
                        }  else {
                            fbq('init', pixelId, advancedMatching);
                            // Removed debug log loadPixel() - Called fbq(init) with advanced matching');
                        }
                    }
                });

                initialized = true;
                // Removed debug log loadPixel() - Set initialized to true');

                // Removed debug log loadPixel() - Calling Utils.fireStaticEvents("facebook")');
                Utils.fireStaticEvents('facebook');
                // Removed debug log loadPixel() - END');

            },

            fireEvent: function (name, data) {
                // Removed debug log Facebook.fireEvent() - START');
                // Removed debug log Facebook.fireEvent() - Event name: ' + name);
                // Removed debug log Facebook.fireEvent() - Data:', data);
                // Removed debug log Facebook.fireEvent() - Initialized: ' + initialized);
                // Removed debug log Facebook.fireEvent() - Is enabled: ' + this.isEnabled());

                if (!initialized || !this.isEnabled()) {
                    // Removed debug log Facebook.fireEvent() - EXITING: Not initialized or not enabled');
                    return false;
                }

                data.delay = data.delay || 0;
                data.params = data.params || {};
                // Removed debug log Facebook.fireEvent() - Delay: ' + data.delay);
                // Removed debug log Facebook.fireEvent() - Params:', data.params);

                if (data.delay === 0) {
                    // Removed debug log Facebook.fireEvent() - No delay, calling fireEvent() immediately');
                    fireEvent(name, data);
                } else {
                    // Removed debug log Facebook.fireEvent() - Delay set to ' + data.delay + ' seconds, scheduling setTimeout');
                    setTimeout(function (name, params) {
                        // Removed debug log Facebook.fireEvent() - setTimeout callback executing');
                        fireEvent(name, params);
                    }, data.delay * 1000, name, data);
                }
                
                // Removed debug log Facebook.fireEvent() - END. Returning true');
                return true;

            },


            onWooAddToCartOnButtonEvent: function (product_id) {
                window.ofPysWooProductData = window.ofPysWooProductData || [];
                
                // Compatibility: Map 'facebook' to 'orderflow_facebook' for key lookup
                var tagKey = this.tag();
                if (tagKey === 'facebook' && options.dynamicEvents && options.dynamicEvents.woo_add_to_cart_on_button_click && options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty('orderflow_facebook')) {
                    tagKey = 'orderflow_facebook';
                }
                
                if(!options.hasOwnProperty('dynamicEvents') || !options.dynamicEvents || !options.dynamicEvents.hasOwnProperty('woo_add_to_cart_on_button_click') || !options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(tagKey)) {
                    return;
                }

                if (window.ofPysWooProductData.hasOwnProperty(product_id)) {
                    // Compatibility: Check for both 'facebook' and 'orderflow_facebook' keys
                    var productDataKey = null;
                    if (window.ofPysWooProductData[product_id].hasOwnProperty('orderflow_facebook')) {
                        productDataKey = 'orderflow_facebook';
                    } else if (window.ofPysWooProductData[product_id].hasOwnProperty('facebook')) {
                        productDataKey = 'facebook';
                    }
                    
                    if (productDataKey) {
                        // Clone the event object
                        var event = Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[tagKey]);
                        
                        // Ensure event.params exists
                        if (!event.params) {
                            event.params = {};
                        }
                        
                        // Check if product data params is an array (empty array) or object
                        var productParams = window.ofPysWooProductData[product_id][productDataKey].params;
                        if (Array.isArray(productParams) && productParams.length === 0) {
                            // Try to get params from the product data structure itself
                            var productData = window.ofPysWooProductData[product_id][productDataKey];
                            if (productData && productData.data && productData.data.params) {
                                productParams = productData.data.params;
                            }
                        }
                        
                        // Copy all product params to event params
                        // This will copy category_name, content_ids, content_name, content_type, contents, currency, value, etc.
                        if (productParams && !Array.isArray(productParams) && Object.keys(productParams).length > 0) {
                            Utils.copyProperties(productParams, event.params);
                        }
                        
                        // Store product_id in event params for fireEvent to use
                        if (!event.params.post_id && product_id) {
                            event.params.post_id = product_id;
                        }
                        
                        // Copy pixelIds if available
                        if (window.ofPysWooProductData[product_id][productDataKey].pixelIds) {
                            event.pixelIds = window.ofPysWooProductData[product_id][productDataKey].pixelIds;
                        }
                        
                        this.fireEvent(event.name, event);
                    }
                }
            },

            onWooAddToCartOnSingleEvent: function (product_id, qty, product_type, $form) {
                // Removed debug log ========== onWooAddToCartOnSingleEvent() START ==========');
                // Removed debug log Step 1: Function called');
                // Removed debug log Step 1a: product_id:', product_id);
                // Removed debug log Step 1b: qty:', qty);
                // Removed debug log Step 1c: product_type:', product_type);
                // Removed debug log Step 1d: $form:', $form);

                // Removed debug log Step 2: Initializing window.ofPysWooProductData');
                window.ofPysWooProductData = window.ofPysWooProductData || [];
                // Removed debug log Step 3: window.ofPysWooProductData:', window.ofPysWooProductData);
                
                // Removed debug log Step 4: Checking dynamicEvents availability');
                // Removed debug log Step 4a: options.hasOwnProperty("dynamicEvents"):', options.hasOwnProperty('dynamicEvents'));
                // Removed debug log Step 4b: options.dynamicEvents exists:', !!options.dynamicEvents);
                // Removed debug log Step 4c: woo_add_to_cart_on_button_click exists:', options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty('woo_add_to_cart_on_button_click'));
                
                // Compatibility: Map 'facebook' to 'orderflow_facebook' for key lookup
                var tagKey = this.tag();
                if (tagKey === 'facebook' && options.dynamicEvents && options.dynamicEvents.woo_add_to_cart_on_button_click && options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty('orderflow_facebook')) {
                    tagKey = 'orderflow_facebook';
                    // Removed debug log Step 4d: Mapped "facebook" to "orderflow_facebook" for compatibility');
                }
                // Removed debug log Step 4e: Using tagKey:', tagKey);
                // Removed debug log Step 4f: this.tag():', this.tag());
                // Removed debug log Step 4g: hasOwnProperty(tagKey):', options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty('woo_add_to_cart_on_button_click') && options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(tagKey));
                // Removed debug log Step 4h: Available keys in woo_add_to_cart_on_button_click:', options.dynamicEvents && options.dynamicEvents.woo_add_to_cart_on_button_click ? Object.keys(options.dynamicEvents.woo_add_to_cart_on_button_click) : 'N/A');
                
                if(!options.hasOwnProperty('dynamicEvents') || !options.dynamicEvents || !options.dynamicEvents.hasOwnProperty('woo_add_to_cart_on_button_click') || !options.dynamicEvents.woo_add_to_cart_on_button_click.hasOwnProperty(tagKey)) {
                    // Removed debug log Step 5: EXITING - dynamicEvents check failed');
                    return;
                }
                
                // Removed debug log Step 6: Cloning event data');
                var event = options.dynamicEvents && options.dynamicEvents.woo_add_to_cart_on_button_click ? Utils.clone(options.dynamicEvents.woo_add_to_cart_on_button_click[tagKey]) : null;
                // Removed debug log Step 7: Event cloned:', event);
                
                if (!event) {
                    // Removed debug log Step 8: EXITING - event is null');
                    return;
                }
                
                // Removed debug log Step 9: Event data found, continuing...');

                // Removed debug log Step 10: Checking if variable product');
                // Removed debug log Step 10a: product_type === Utils.PRODUCT_VARIABLE:', product_type === Utils.PRODUCT_VARIABLE);
                // Removed debug log Step 10b: options.facebook.wooVariableAsSimple:', options.facebook && options.facebook.wooVariableAsSimple);
                
                if (product_type === Utils.PRODUCT_VARIABLE && !options.facebook.wooVariableAsSimple) {
                    // Removed debug log Step 11: Variable product detected, getting variation_id');
                    product_id = parseInt($form.find('input[name="variation_id"]').val());
                    // Removed debug log Step 12: Updated product_id (variation_id):', product_id);
                } else {
                    // Removed debug log Step 11: Not a variable product or using as simple');
                }

                // Removed debug log Step 13: Checking if product data exists for product_id:', product_id);
                // Removed debug log Step 13a: window.ofPysWooProductData.hasOwnProperty(product_id):', window.ofPysWooProductData.hasOwnProperty(product_id));
                // Removed debug log Step 13b: Available product IDs:', Object.keys(window.ofPysWooProductData));
                
                if (window.ofPysWooProductData.hasOwnProperty(product_id)) {
                    // Removed debug log Step 14: Product data found');
                    // Removed debug log Step 14a: Product data:', window.ofPysWooProductData[product_id]);
                    // Removed debug log Step 14b: Available keys in product data:', Object.keys(window.ofPysWooProductData[product_id]));
                    // Removed debug log Step 15: Checking if facebook/orderflow_facebook data exists');
                    // Removed debug log Step 15a: hasOwnProperty("facebook"):', window.ofPysWooProductData[product_id].hasOwnProperty('facebook'));
                    // Removed debug log Step 15b: hasOwnProperty("orderflow_facebook"):', window.ofPysWooProductData[product_id].hasOwnProperty('orderflow_facebook'));
                    
                    // Compatibility: Check for both 'facebook' and 'orderflow_facebook' keys
                    var productDataKey = null;
                    if (window.ofPysWooProductData[product_id].hasOwnProperty('orderflow_facebook')) {
                        productDataKey = 'orderflow_facebook';
                        // Removed debug log Step 15c: Using "orderflow_facebook" key');
                    } else if (window.ofPysWooProductData[product_id].hasOwnProperty('facebook')) {
                        productDataKey = 'facebook';
                        // Removed debug log Step 15c: Using "facebook" key');
                    }
                    
                    if (productDataKey) {
                        // Removed debug log Step 16: Facebook data found with key:', productDataKey);
                        // Removed debug log Step 16a: Facebook data:', window.ofPysWooProductData[product_id][productDataKey]);
                        // Removed debug log Step 17: Copying product params to event');
                        Utils.copyProperties(window.ofPysWooProductData[product_id][productDataKey].params, event.params);
                        // Removed debug log Step 18: Event params after copy:', event.params);

                        // Removed debug log Step 19: Processing grouped/bundle products');
                        var groupValue = 0;
                        if(product_type === Utils.PRODUCT_GROUPED ) {
                            // Removed debug log Step 20: Processing GROUPED product');
                            $form.find(".woocommerce-grouped-product-list .qty").each(function(index){
                                var childId = $(this).attr('name').replaceAll("quantity[","").replaceAll("]","");
                                var quantity = parseInt($(this).val());
                                if(isNaN(quantity)) {
                                    quantity = 0;
                                }
                                // Removed debug log Step 20a: Child ID:', childId, ', Quantity:', quantity);
                                var childItem = window.ofPysWooProductData[product_id][productDataKey].grouped[childId];
                                // Removed debug log Step 20b: Child item data:', childItem);

                                if(quantity == 0) {
                                    event.params.content_ids.forEach(function(el,index,array) {
                                        if(el == childItem.content_id) {
                                            array.splice(index, 1);
                                        }
                                    });
                                }

                                if(event.params.hasOwnProperty('contents')) {
                                    event.params.contents.forEach(function(el,index,array) {
                                        if(el.id == childItem.content_id) {
                                            if(quantity > 0){
                                                el.quantity = quantity;
                                            } else {
                                                array.splice(index, 1);
                                            }
                                        }
                                    });
                                }


                                groupValue += childItem.price * quantity;
                            });
                            // Removed debug log Step 21: Group value calculated:', groupValue);
                            if(groupValue == 0) {
                                // Removed debug log Step 22: EXITING - No items selected (groupValue = 0)');
                                return; // skip if no items selected
                            }
                        }

                        // Removed debug log Step 23: Checking value customization options');
                        // maybe customize value option
                        if (options.hasOwnProperty('woo') && options.woo && options.woo.addToCartOnButtonValueEnabled && options.woo.addToCartOnButtonValueOption !== 'global') {
                            // Removed debug log Step 24: Value customization enabled');

                            if(product_type === Utils.PRODUCT_GROUPED) {
                                event.params.value = groupValue;
                                // Removed debug log Step 25: GROUPED - Set value to:', groupValue);
                            } else if(product_type === Utils.PRODUCT_BUNDLE) {
                                var data = $(".bundle_form .bundle_data").data("bundle_form_data");
                                var items_sum = getBundlePriceOnSingleProduct(data);
                                event.params.value = (parseInt(data.base_price) + items_sum )* qty;
                                // Removed debug log Step 25: BUNDLE - Set value to:', event.params.value);
                            } else {
                                event.params.value = event.params.value * qty;
                                // Removed debug log Step 25: SIMPLE - Set value to:', event.params.value);
                            }
                        } else {
                            // Removed debug log Step 24: Value customization disabled or using global');
                        }

                        // Removed debug log Step 26: Updating contents quantity');
                        // only when non Facebook for WooCommerce logic used
                        if (event.params.hasOwnProperty('contents') && product_type !== Utils.PRODUCT_GROUPED) {
                            // Removed debug log Step 27: Updating contents[0].quantity to:', qty);
                            event.params.contents[0].quantity = qty;
                        } else {
                            // Removed debug log Step 27: SKIPPED - No contents or grouped product');
                        }
                        
                        // Removed debug log Step 28: Final event data before fireEvent:', event);
                        // Removed debug log Step 29: Calling this.fireEvent()');
                        // Removed debug log Step 29a: Event name:', event.name);
                        // Removed debug log Step 29b: Event params:', event.params);
                        this.fireEvent(event.name, event);
                        // Removed debug log Step 30: fireEvent() call completed');

                    } else {
                        // Removed debug log Step 16: EXITING - Facebook data not found in product data (neither "facebook" nor "orderflow_facebook" key exists)');
                    }
                } else {
                    // Removed debug log Step 14: EXITING - Product data not found for product_id:', product_id);
                    // Removed debug log Step 14a: Available product IDs in ofPysWooProductData:', Object.keys(window.ofPysWooProductData));
                }
                // Removed debug log ========== onWooAddToCartOnSingleEvent() END ==========');
            },

            onWooRemoveFromCartEvent: function (event) {
                this.fireEvent(event.name, event);
            },
            initEventIdCookies: function (key) {
                var ids = {};
                ids[key] = pys_generate_token(36)
                Cookies.set('pys_fb_event_id', JSON.stringify(ids));
            },
            updateEventId:function(key) {
                var cooData = Cookies.get("pys_fb_event_id")
                if(cooData === undefined) {
                    this.initEventIdCookies(key);
                } else {
                    var data = JSON.parse(cooData);
                    data[key] = pys_generate_token(36);
                    Cookies.set('pys_fb_event_id', JSON.stringify(data) );
                }
            },

            getEventId:function (key) {
                var data = Cookies.get("pys_fb_event_id");
                if(data === undefined) {
                    this.initEventIdCookies(key);
                    data = Cookies.get("pys_fb_event_id");
                }
                return JSON.parse(data)[key];
            },

            sendFacebookRestAPIRequest: function(allData, name, params) {
                if (typeof window.ofPysFacebookRest === 'undefined' || !window.ofPysFacebookRest.restApiUrl) {
                    return;
                }

                var pageTitle = (params && params['page_title']) || (options && options.current_page_title) || document.title || '';
                const restApiData = {
                    event: name,
                    data: JSON.stringify(params),
                    page_title: pageTitle,
                    ids: allData.pixelIds || options.facebook.pixelIds,
                    eventID: allData.eventID,
                    woo_order: allData.woo_order || 0
                };

                // Try sendBeacon first
                if (navigator.sendBeacon) {
                    const formData = new FormData();
                    Object.keys(restApiData).forEach(key => {
                        if (Array.isArray(restApiData[key])) {
                            restApiData[key].forEach(value => {
                                formData.append(key + '[]', value);
                            });
                        } else {
                            formData.append(key, restApiData[key]);
                        }
                    });

                    if (navigator.sendBeacon(window.ofPysFacebookRest.restApiUrl, formData)) {
                        return;
                    }
                }

                // Fallback to fetch
                fetch(window.ofPysFacebookRest.restApiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams(restApiData)
                }).catch(() => {
                    // Fallback to AJAX if fetch fails
                    this.sendAjaxFallback(allData, name, params);
                });
            },

            sendAjaxFallback: function(allData, name, params) {
                var pageTitle = (params && params['page_title']) || (options && options.current_page_title) || document.title || '';
                var json = {
                    action: 'pys_api_event',
                    pixel: 'facebook',
                    event: name,
                    data: params,
                    page_title: pageTitle,
                    ids: allData.pixelIds || options.facebook.pixelIds,
                    eventID: allData.eventID,
                    url: window.location.href,
                    ajax_event: options.ajax_event
                };
                if (allData.hasOwnProperty('woo_order')) {
                    json['woo_order'] = allData.woo_order;
                }

                Utils.sendServerAjaxRequest(options.ajaxUrl, json);
            },
        };

    }(options);

    var getPixelBySlag = function getPixelBySlag(slug) {
        switch (slug) {
            case "facebook": return window.pys.Facebook;
        }
    }

    window.pys = window.pys || {};
    window.pys.Facebook = Facebook;
    window.pys.Utils = Utils;
    window.pys.getPixelBySlag = getPixelBySlag;

    // Export getPixelBySlag globally for backward compatibility
    window.getPixelBySlag = getPixelBySlag;


    $(document).ready(function () {



        if($("#pys_late_event").length > 0) {
            var dirAttr = $("#pys_late_event").attr("dir");
            if (dirAttr) {
                try {
                    var events = JSON.parse(dirAttr);
                } catch (e) {
                    console.warn("Invalid JSON in pys_late_event dir attribute:", e);
                }
            } else {
                console.warn("pys_late_event dir attribute is undefined or empty");
            }
            if (events) {
                for (var key in events) {
                    var event = {};
                    event[events[key].e_id] = [events[key]];
                    if (options.staticEvents.hasOwnProperty(key)) {
                        Object.assign(options.staticEvents[key], event);
                    } else {
                        options.staticEvents[key] = event;
                    }
                }
            }
        }


        if(options.hasOwnProperty('cookie'))
        {
            if(options.cookie.externalID_disabled_by_api || options.cookie.disabled_all_cookie)
            {
                Cookies.remove('pbid')
            }
            if(options.cookie.disabled_advanced_form_data_cookie || options.cookie.disabled_all_cookie)
            {
                Cookies.remove('of_pys_advanced_form_data')
            }
            if(options.cookie.disabled_landing_page_cookie || options.cookie.disabled_all_cookie)
            {
                Cookies.remove('pys_landing_page')
                Cookies.remove('last_pys_landing_page')
            }
            if(options.cookie.disabled_trafficsource_cookie || options.cookie.disabled_all_cookie)
            {
                Cookies.remove('pysTrafficSource')
                Cookies.remove('last_pysTrafficSource')
            }
            if(options.cookie.disabled_first_visit_cookie || options.cookie.disabled_all_cookie)
            {
                Cookies.remove('pys_first_visit')

            }
            if(options.cookie.disabled_utmTerms_cookie || options.cookie.disabled_all_cookie)
            {
                $.each(Utils.utmTerms, function (index, name) {
                    Cookies.remove('pys_' + name)
                });
                $.each(Utils.utmTerms, function (index, name) {
                    Cookies.remove('last_pys_' + name)
                });
            }
            if(options.cookie.disabled_utmId_cookie || options.cookie.disabled_all_cookie)
            {
                $.each(Utils.utmId,function(index,name) {
                    Cookies.remove('pys_' + name)
                })
                $.each(Utils.utmId,function(index,name) {
                    Cookies.remove('last_pys_' + name)
                });
            }
        }


        if (options.gdpr.cookie_law_info_integration_enabled) {
            var cli_cookie = Cookies.get('cookieyes-consent') ?? Cookies.get('viewed_cookie_policy');

            if (typeof cli_cookie !== 'undefined') {
                if (cli_cookie === Cookies.get('cookieyes-consent') && getCookieYes('analytics') == 'yes') {
                    Utils.manageCookies();
                } else if (cli_cookie === Cookies.get('viewed_cookie_policy') && cli_cookie == 'yes') {
                    Utils.manageCookies();
                }
            }
        }

        if ( options.gdpr.consent_magic_integration_enabled && typeof CS_Data !== "undefined" ) {
            if ( CS_Data.cs_script_cat.pys == CS_Data.cs_necessary_cat_id || CS_Data.cs_script_cat.pys == 0 ) {
                Utils.manageCookies();
            } else if ( Cookies.get( 'cs_enabled_cookie_term' + CS_Data.test_prefix + '_' + CS_Data.cs_script_cat.pys ) == 'yes' ) {
                Utils.manageCookies();
            }
        } else {
            Utils.manageCookies();
        }

        Utils.setupGdprCallbacks();


        // setup Dynamic events
        $.each(options.triggerEventTypes, function (triggerType, events) {

            $.each(events, function (eventId, triggers) {

                switch (triggerType) {
                    case 'url_click':
                        //@see: Utils.setupURLClickEvents()
                        break;

                    case 'css_click':
                        Utils.setupCSSClickEvents(eventId, triggers);
                        break;

                    case 'css_mouseover':
                        Utils.setupMouseOverClickEvents(eventId, triggers);
                        break;

                    case 'scroll_pos':
                        Utils.setupScrollPosEvents(eventId, triggers);
                        break;
                }

            });

        });
        // setup WooCommerce events
        if (options.hasOwnProperty('woo') && options.woo && options.woo.enabled) {

            // WooCommerce AddToCart
            // Removed debug log Setting up WooCommerce AddToCart events');
            // Removed debug log dynamicEvents check:', options.hasOwnProperty('dynamicEvents'));
            // Removed debug log dynamicEvents value:', options.dynamicEvents);
            // Removed debug log woo_add_to_cart_on_button_click exists:', options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click"));
            // Removed debug log options.woo:', options.woo);
            // Removed debug log addToCartCatchMethod:', options.woo && options.woo.addToCartCatchMethod);
            
            if (options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click")
                && options.woo.hasOwnProperty("addToCartCatchMethod")
                && options.woo.addToCartCatchMethod === "add_cart_js"
            ) {
                // Removed debug log AddToCart setup conditions met - Setting up click handlers');

                // Loop, any kind of "simple" product, except external
                $('.add_to_cart_button:not(.product_type_variable,.product_type_bundle,.single_add_to_cart_button)').on("click",function (e) {
                    // Removed debug log ========== ADD TO CART BUTTON CLICKED (SHOP PAGE) ==========');
                    // Removed debug log Step 1: Click event triggered on shop page');
                    // Removed debug log Step 2: Button element:', this);
                    // Removed debug log Step 3: Button classes:', $(this).attr('class'));

                    var product_id = $(this).data('product_id');
                    // Removed debug log Step 4: Extracted product_id from data attribute:', product_id);
                    // Removed debug log Step 5: product_id type:', typeof product_id);
                    // Removed debug log Step 6: product_id is undefined?', typeof product_id === 'undefined');
                    
                    if (typeof product_id !== 'undefined') {
                        // Removed debug log Step 7: product_id is valid, proceeding...');
                        // Removed debug log Step 8: Checking dynamicEvents availability');
                        // Removed debug log Step 8a: options.hasOwnProperty("dynamicEvents"):', options.hasOwnProperty('dynamicEvents'));
                        // Removed debug log Step 8b: options.dynamicEvents exists:', !!options.dynamicEvents);
                        // Removed debug log Step 8c: woo_add_to_cart_on_button_click exists:', options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click"));
                        
                        if (options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click")) {
                            // Removed debug log Step 9: Generating event ID');
                            var tmpEventID = pys_generate_token();
                            // Removed debug log Step 10: Generated event ID:', tmpEventID);
                            // Removed debug log Step 11: Setting eventID for all dynamic events');
                            // Removed debug log Step 11a: dynamicEvents.woo_add_to_cart_on_button_click:', options.dynamicEvents.woo_add_to_cart_on_button_click);
                            
                            $.each(options.dynamicEvents.woo_add_to_cart_on_button_click, function (i, tag) {
                                // Removed debug log Step 11b: Setting eventID for tag index:', i, 'Tag:', tag);
                                tag.eventID = tmpEventID;
                            });
                            // Removed debug log Step 12: Event IDs set, calling Facebook.onWooAddToCartOnButtonEvent');
                        } else {
                            // Removed debug log Step 9: SKIPPED - dynamicEvents.woo_add_to_cart_on_button_click not available');
                        }
                        
                        if (typeof product_id !== 'undefined') {
                            // Removed debug log Step 13: Calling Facebook.onWooAddToCartOnButtonEvent with product_id:', product_id);
                            Facebook.onWooAddToCartOnButtonEvent(product_id);
                            // Removed debug log Step 14: Facebook.onWooAddToCartOnButtonEvent() call completed');
                        } else {
                            // Removed debug log Step 13: SKIPPED - product_id is undefined');
                        }
                    } else {
                        // Removed debug log Step 7: EXITING - product_id is undefined');
                    }
                    // Removed debug log ========== ADD TO CART BUTTON CLICK HANDLER END ==========');
                });

                // Single Product
                // tap try to https://stackoverflow.com/questions/30990967/on-tap-click-event-firing-twice-how-to-avoid-it
                //  $(document) not work
                $('body').onFirst('click','button.single_add_to_cart_button,.single_add_to_cart_button',function (e) {
                    // Removed debug log ========== SINGLE ADD TO CART BUTTON CLICKED ==========');
                    // Removed debug log Step 1: Click event triggered on single product page');
                    // Removed debug log Step 2: Button element:', this);

                    var $button = $(this);
                    // Removed debug log Step 3: Button jQuery object:', $button);
                    // Removed debug log Step 4: Button has disabled class?', $button.hasClass('disabled'));

                    if ($button.hasClass('disabled')) {
                        // Removed debug log Step 5: EXITING - Button is disabled');
                        return;
                    }

                    // Removed debug log Step 6: Getting form element');
                    var $form = $button.closest('form');
                    // Removed debug log Step 7: Form element:', $form);
                    // Removed debug log Step 8: Form length:', $form.length);

                    // Removed debug log Step 9: Determining product type');
                    var product_type = Utils.PRODUCT_SIMPLE;
                    // Removed debug log Step 10: Default product_type:', product_type);

                    if ($form.length === 0) {
                        // Removed debug log Step 11: EXITING - Form not found');
                        return ;
                    } else if ($form.hasClass('variations_form')) {
                        product_type = Utils.PRODUCT_VARIABLE;
                        // Removed debug log Step 12: Product type: VARIABLE');
                    } else if($form.hasClass('bundle_form')) {
                        product_type = Utils.PRODUCT_BUNDLE;
                        // Removed debug log Step 12: Product type: BUNDLE');
                    } else if($form.hasClass('grouped_form')) {
                        product_type = Utils.PRODUCT_GROUPED;
                        // Removed debug log Step 12: Product type: GROUPED');
                    } else {
                        // Removed debug log Step 12: Product type: SIMPLE');
                    }




                    // Removed debug log Step 13: Extracting product_id and quantity');
                    var product_id;
                    var qty;

                    if (product_type === Utils.PRODUCT_GROUPED) {
                        qty = 1;
                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
                        // Removed debug log Step 14: GROUPED product - product_id:', product_id, ', qty:', qty);
                    } else if (product_type === Utils.PRODUCT_VARIABLE) {
                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
                        var qtyTag = $form.find('input[name="quantity"]');
                        if(qtyTag.length <= 0) {
                            qtyTag = $form.find('select[name="quantity"]');
                        }
                        qty = parseInt(qtyTag.val());
                        // Removed debug log Step 14: VARIABLE product - product_id:', product_id, ', qty:', qty);
                    } else {
                        product_id = parseInt($form.find('*[name="add-to-cart"]').val());
                        var qtyTag = $form.find('input[name="quantity"]');
                        if(qtyTag.length <= 0) {
                            qtyTag = $form.find('select[name="quantity"]');
                        }
                        qty = parseInt(qtyTag.val());
                        // Removed debug log Step 14: SIMPLE product - product_id:', product_id, ', qty:', qty);
                    }

                    // Removed debug log Step 15: Checking dynamicEvents for event ID generation');
                    if(options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty("woo_add_to_cart_on_button_click")){
                        // Removed debug log Step 16: Generating event ID');
                        var tmpEventID = pys_generate_token();
                        // Removed debug log Step 17: Generated event ID:', tmpEventID);
                        $.each(options.dynamicEvents.woo_add_to_cart_on_button_click, function (i, tag) {
                            tag.eventID = tmpEventID;
                        });
                        // Removed debug log Step 18: Event IDs set');
                    } else {
                        // Removed debug log Step 16: SKIPPED - dynamicEvents not available');
                    }

                    // Removed debug log Step 19: Calling Facebook.onWooAddToCartOnSingleEvent');
                    // Removed debug log Step 19a: product_id:', product_id);
                    // Removed debug log Step 19b: qty:', qty);
                    // Removed debug log Step 19c: product_type:', product_type);
                    Facebook.onWooAddToCartOnSingleEvent(product_id, qty, product_type, $form);
                    // Removed debug log Step 20: Facebook.onWooAddToCartOnSingleEvent() call completed');
                    // Removed debug log ========== SINGLE ADD TO CART BUTTON CLICK HANDLER END ==========');

                });

            }

            // WooCommerce RemoveFromCart
            if (options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty("woo_remove_from_cart") && options.woo && options.woo.hasOwnProperty('removeFromCartSelector')) {

                $('body').on('click', options.woo.removeFromCartSelector, function (e) {

                    var $a = $(e.currentTarget),
                        href = $a.attr('href');

                    // extract cart item hash from remove button URL
                    var regex = new RegExp("[\\?&]remove_item=([^&#]*)"),
                        results = regex.exec(href);

                    if (results !== null) {

                        var item_hash = results[1];

                        if (options.hasOwnProperty('dynamicEvents') && options.dynamicEvents && options.dynamicEvents.hasOwnProperty("woo_remove_from_cart") && options.dynamicEvents["woo_remove_from_cart"].hasOwnProperty(item_hash)) {
                            var events = options.dynamicEvents["woo_remove_from_cart"][item_hash];
                            Utils.fireEventForAllPixel("onWooRemoveFromCartEvent",events)
                        }

                    }

                });
            }
        }


        // load pixel APIs
        // Removed debug log Document ready - About to call Utils.loadPixels()');
        Utils.loadPixels();
        // Removed debug log Document ready - Utils.loadPixels() called');
        // setup Enrich content
        if(Utils.isCheckoutPage()) {
            Utils.addCheckoutFields();
        }
    });

}(jQuery, ofPysOptions);

function pys_generate_token() {
    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    );
}

function getBundlePriceOnSingleProduct(data) {
    var items_sum = 0;
    jQuery(".bundle_form .bundled_product").each(function(index){
        var id = jQuery(this).find(".cart").data("bundled_item_id");
        var item_price = data.prices[id];
        var item_quantity = jQuery(this).find(".bundled_qty").val();
        if(!jQuery(this).hasClass("bundled_item_optional") ||
            jQuery(this).find(".bundled_product_optional_checkbox input").prop('checked')) {
            items_sum += item_price*item_quantity;
        }
    });
    return items_sum;
}
function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};
function getCookieYes(key) {
    const cookiesObj = document.cookie
        .split(";")
        .reduce((ac, cv) => {
            const [k, v] = cv.split("=");
            if (k && v) ac[k.trim()] = v;
            return ac;
        }, {});
    const consentCookie = cookiesObj["cookieyes-consent"] || cookiesObj["wt_consent"];
    if (!consentCookie) return undefined;
    const { [key]: value } = consentCookie
        .split(",")
        .reduce((obj, pair) => {
            const [k, v] = pair.split(":");
            if (k && v) obj[k] = v;
            return obj;
        }, {});
    return value;
}
function getRootDomain(useSubdomain = false) {
    const hostname = window.location.hostname; // Get the current hostname
    // Check if tldjs is defined before using it
    if (typeof tldjs === "undefined") {
        console.warn("tldjs is not defined");
        return hostname; // Return hostname as a fallback
    }

    const rootDomain = tldjs.getDomain(hostname); // Use tldjs to extract the root domain

    // Return the root domain with or without a leading dot based on useSubdomain
    return rootDomain ? (useSubdomain ? '.' + rootDomain : rootDomain) : hostname;
}