import React, { useContext, useState } from "react";
import mixpanel from "mixpanel-browser";
import { LocalLogicTracking } from "~/tracking/utils/classes/Methods";
import { getDeviceId, getSessionId } from "~/tracking/utils/user";
const trackingContext = React.createContext({});
const useTracking = () => useContext(trackingContext);
/**
 * This function has to be called once and first before trying to send analytics events
 *
 * @param projectToken Project token
 */
function initializeAnalytics(projectToken) {
    try {
        mixpanel.init(projectToken, {
            track_pageview: false,
            persistence: "localStorage",
        });
    }
    catch (_error) {
        // Do nothing. This is a best effort function
    }
}
const TrackingProvider = ({ children, trackingPipelineSettings, analyticsSettings, attributes = {}, meta, flags, }) => {
    var _a, _b, _c;
    const tracking = LocalLogicTracking((_a = trackingPipelineSettings === null || trackingPipelineSettings === void 0 ? void 0 : trackingPipelineSettings.apiKey) !== null && _a !== void 0 ? _a : "");
    const [defaultAnalyticsAttributes] = useState({
        ll_product_name: meta.productName,
        ll_product_version: meta.productVersion,
        ll_client_id: meta.clientId,
        ll_locale: attributes.locale,
        ll_location_lat: (_b = attributes.location) === null || _b === void 0 ? void 0 : _b.lat,
        ll_location_lng: (_c = attributes.location) === null || _c === void 0 ? void 0 : _c.lng,
    });
    /**
     * Posts an event to our own Tracking API
     *
     * @param eventType The event type
     * @param eventAttributes Extra data to be tracked with the event
     */
    const postEvent = ({ eventType, eventAttributes }) => {
        const metaValues = {
            product_version: meta.productVersion || "not_defined",
            product_name: meta.productName || "",
            client_id: meta.clientId,
            device_id: getDeviceId(),
            session_id: getSessionId(),
        };
        const eventBody = {
            event_type: eventType,
            event_version: "1.0.0",
            meta: metaValues,
            attributes: Object.assign({ event_attributes: eventAttributes }, attributes),
        };
        if (flags === null || flags === void 0 ? void 0 : flags.isDebugMode) {
            console.info("Tracking event:", eventBody);
            return;
        }
        tracking.postEvent(eventBody);
    };
    /**
     * Tracks an event with a third party analytics service (Mixpanel, GA4, etc).
     * This is currently an experimental feature.
     *
     * @param eventType The event type
     * @param eventAttributes Extra data to be tracked with the event
     */
    const trackAnalyticsEvent = ({ eventName, eventAttributes = {}, }) => {
        if (typeof analyticsSettings === "undefined" ||
            analyticsSettings.tracker !== "mixpanel") {
            return;
        }
        // Mixpanel debug mode still sends mixpanel events. There's no reason to really use it
        if (analyticsSettings.printDebugMode) {
            console.info("Mixpanel Debug:", {
                event: eventName,
                projectToken: analyticsSettings.key,
                properties: Object.assign(Object.assign({}, eventAttributes), defaultAnalyticsAttributes),
            });
        }
        if (analyticsSettings.isDebugMode) {
            return;
        }
        try {
            mixpanel.track(eventName, Object.assign(Object.assign({}, eventAttributes), defaultAnalyticsAttributes));
        }
        catch (_error) {
            // Do nothing
            // Sometimes the init function takes longer than expected
            // This makes the first tracking call fail. We're ok with that.
        }
    };
    return (React.createElement(trackingContext.Provider, { value: { postEvent, trackAnalyticsEvent } }, children));
};
export { useTracking, TrackingProvider, initializeAnalytics };
//# sourceMappingURL=index.js.map