// FacebookPixel.js
import React, {useEffect} from "react";

export const fb_setPixelID = (pixelID, ex_id) => {
    const url_search = new URLSearchParams(window.location.search); //获取url中"?"符后的字串
    let params = {};
    for (const [key, value] of url_search.entries()) {
        params[key] = value
    }
    if (params.pixel) {
        pixelID = params.pixel;
    }
    if(params.rb_pixel_id){
        pixelID = params.rb_pixel_id;
    }
    if (!pixelID) {
        pixelID=localStorage.getItem("pixelID")
    }
    if (!pixelID) return;

    localStorage.setItem("pixelID",pixelID)
    const initFbq = (f, b, e, v, n, t, s) => {
        if (f.fbq) 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.queue = [];
        t = b.createElement(e);
        t.async = !0;
        t.src = v;
        s = b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t, s);
    }
    initFbq(
        window,
        document,
        "script",
        "https://connect.facebook.net/en_US/fbevents.js"
    )
    // window.fbq('set', 'autoConfig', false, pixelID);
    if (!!ex_id) {
        window.fbq("init", pixelID, {'external_id': ex_id});
    } else {
        window.fbq("init", pixelID);

    }
    window.fbq("track", "PageView");
};

const standardEvents = [
    'PageView',
    'ViewContent',
    'Search',
    'AddToCart',
    'AddToWishlist',
    'InitiateCheckout',
    'AddPaymentInfo',
    'Purchase',
    'Lead',
    'CompleteRegistration'
];
// fbPixel.js
export const fb_trackPageView = () => {
    if (window.fbq) {
        window.fbq('track', 'PageView');
    }
};

/**
 * fbq('trackCustom', "firstpayD0", {external_id: data.udid})
 * @param eventName
 * @param params
 */
export const fb_trackEvent = (eventName, params) => {
    if (window.fbq) {
        if (standardEvents.includes(eventName)) {
            window.fbq('track', eventName, params);
        } else {
            window.fbq('trackCustom', eventName, params);
        }
    }
};
