import { fb_trackEvent, fb_trackPageView, fb_setPixelID } from "./FacebookPixel";
import { gg_setTagID, gtrack } from "./GoogleAnalytics";
import { kwai_setPixelID, kwai_trackEvent } from "./KwaiPixel";
import { loadInfoNew } from "./ApkPromote";
import { initializeFirebaseAnalytics, fa_trackEvent } from "./FirebaseAnalytics";
import {localStorageGet, localStorageSet} from "@utils/helpers"; // Import Firebase functions


 const initTrackAllLocal = (pf_type, pf_id, ex_id) => {

    if (pf_type === "fb") {
        fb_setPixelID(pf_id, ex_id);
    } else if (pf_type === "kw") {
        kwai_setPixelID(pf_id, ex_id);
    } else if (pf_type === "gg") {
        pf_id = pf_id.split("|");
        gg_setTagID(pf_id[0], pf_id[1]);
    } else if (pf_type === 'apk') {
        // apk下载需要再进行一步
        loadInfoNew(pf_id, ex_id);
        return;
    } else if (pf_type === 'fire') {
        // Initialize Firebase Analytics
        let vars=global.getUrlvars()
        if(typeof vars=="string")vars=JSON.parse(vars)

        if(!vars.firebase_app_id) {
            let fires = localStorageGet("myfire", "{}");
            vars = JSON.parse(fires);
        }

        if(!!vars.firebase_app_id) {
            localStorageSet("myfire",JSON.stringify(vars))
            // const measurementId = vars.measurement_id||""; // Assuming pf_id is measurementId
            const apiSecret = vars.api_secret; // Assuming ex_id is apiSecret
            const firebaseAppId = vars.firebase_app_id; // Replace with your Firebase App ID
            const clientId = vars.app_instance_id; // Replace with your Firebase App ID
            initializeFirebaseAnalytics("", apiSecret, firebaseAppId, clientId);
        }
    }

    window.addEventListener('installready', function () {
        // Show your own installation UI
        if (pf_type === "fb") {
            trackEvent("InstallPWA");
        } else if (pf_type === "kw") {
            trackEvent("download");
        } else if (pf_type === "gg") {
            trackEvent("file_download");
        } else if (pf_type === "fire") {
            fa_trackEvent("install_ready", {}); // Example event for Firebase
        }
    });
}

export const initTrackAll = (pf_type, pf_id, ex_id) => {
     try{
         initTrackAllLocal(pf_type, pf_id, ex_id);
     }catch (e) {
         console.error(e)
     }
}

export const trackPageView = () => {
    if (window.fbq && global.pf && global.pf.type === 'fb') {
        fb_trackEvent();
    }
};

export const trackEvent = (eventName, params) => {
    const pf_type = global.pf && global.pf.type; // Get the platform type

    // Handle Google Analytics events
    if (pf_type === 'gg') {
        if (eventName === "pay") {
            let data = params;
            if (data.first) {
                if (!!data.isd0) {
                    gtrack("d0", { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
                }
                gtrack("d1", { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
            } else if (!data.isd0) {
                gtrack("repay", { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
            }
            gtrack('purchase', { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
        } else {
            gtrack(eventName, params);
        }
    }

    // Handle Facebook events
    if (pf_type === 'fb') {
        if (eventName === "pay") {
            let data = params;
            if (data.first) {
                if (!!data.isd0) {
                    fb_trackEvent("firstpayD0", { external_id: data.udid });
                    fb_trackEvent('AddToWishlist', {
                        value: data.golds,
                        currency: global.currency,
                        external_id: data.udid
                    });
                }
                fb_trackEvent("firstpayD1", { external_id: data.udid });
                fb_trackEvent('AddToCart', {
                    value: data.golds,
                    currency: global.currency,
                    external_id: data.udid
                });
            } else if (!data.isd0) {
                fb_trackEvent("payagain", { external_id: data.udid });
                fb_trackEvent('InitiateCheckout', {
                    value: data.golds,
                    currency: global.currency,
                    external_id: data.udid
                });
            }
            fb_trackEvent('Purchase', {
                value: data.golds,
                currency: global.currency,
                external_id: data.udid
            });
        } else if (eventName === "CompleteRegistration") {
            fb_trackEvent('CompleteRegistration', params);
        } else {
            fb_trackEvent(eventName, params);
        }
    }

    // Handle Kwai events
    if (pf_type === 'kw') {
        if (eventName === "pay") {
            let data = params;
            let addParams = {
                value: data.golds,
                currency: global.currency,
                mapping_id: data.udid
            };
            if (data.first) {
                if (!!data.isd0) {
                    kwai_trackEvent('firstDeposit', addParams);
                    kwai_trackEvent('addToWishlist', addParams);
                }
                kwai_trackEvent('addToCart', addParams);
            } else if (!data.isd0) {
                kwai_trackEvent("payagain", addParams);
                kwai_trackEvent('initiatedCheckout', addParams);
            }
            kwai_trackEvent('purchase', addParams);
        } else {
            if (eventName === 'CompleteRegistration') eventName = 'completeRegistration';
            kwai_trackEvent(eventName, params);
        }
    }

    // Check if the platform is Firebase and send the event
    if (pf_type === 'fire') {
        if (eventName === "pay") {
            let data = params;
            let addParams={
                price: data.golds,
                currency: global.currency,
                mapping_id: data.udid
            }
            if (data.first) {
                if (!!data.isd0) {
                    fa_trackEvent('first_purchase_today', addParams);
                    // fa_trackEvent('first_purchase', addParams);
                }
            } else if (!data.isd0) {
                fa_trackEvent("purchase_again", addParams);
            }
            fa_trackEvent('purchase',addParams );
        } else if (eventName === "CompleteRegistration") {
            fa_trackEvent('registration_success', { external_id: params.udid });
        } else if (eventName === "EnterGame") {
            fa_trackEvent('enter_game', params);
        } else {
            fa_trackEvent(eventName, params); // Send other events to Firebase
        }
    }
};
