// FirebaseAnalytics.js
let firebaseAnalyticsInstance = null;

class FirebaseAnalytics {
    /**
     * @param {Object} config
     * @param {string} config.measurementId - Measurement ID (例如：G-XXXXXXXXXX)
     * @param {string} config.apiSecret - API Secret
     * @param {string} config.firebaseAppId - Firebase App ID
     * @param {string} config.clientId - 客户端ID，通常来自客户端 cookie 或设备唯一标识
     */
    constructor({ measurementId, apiSecret, firebaseAppId, clientId }) {
        this.measurementId = measurementId;
        this.apiSecret = apiSecret;
        this.firebaseAppId = firebaseAppId;
        this.clientId = clientId;
        // 构造上报的 URL，参考 Measurement Protocol 规范
        this.endpoint = `https://www.google-analytics.com/mp/collect?firebase_app_id=${this.firebaseAppId}&api_secret=${this.apiSecret}`;
    }

    /**
     * 上报事件到 Firebase Analytics
     * @param {string} eventName - 事件名称，例如 "user_sign_in"
     * @param {Object} params - 事件参数（键值对），例如 { page: 'home', duration: 123 }
     * @returns {Promise<Response>} 返回 fetch 的响应结果
     */
    async sendEvent(eventName, params = {}) {
        // 构造 Measurement Protocol 所要求的 payload
        const payload = {
            app_instance_id: this.clientId,
            events: [
                {
                    name: eventName,
                    params: params
                }
            ]
        };

        try {
            const response = await fetch(this.endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });
            if (!response.ok) {
                throw new Error(`事件上报失败，状态码：${response.status}`);
            }
            return response;
        } catch (error) {
            console.error('FirebaseAnalytics 上报错误：', error);
            throw error;
        }
    }
}

// Initialize Firebase Analytics
const initializeFirebaseAnalytics = (measurementId, apiSecret, firebaseAppId='',clientId='') => {
    if (!firebaseAnalyticsInstance) {
        firebaseAnalyticsInstance = new FirebaseAnalytics({measurementId, apiSecret, firebaseAppId,clientId});
        console.log('Firebase Analytics initialized');
    } else {
        console.warn('Firebase Analytics is already initialized');
    }
};

// Interface function for external calls
const fa_trackEvent = (eventName, eventParams) => {
    if (!firebaseAnalyticsInstance) {
        console.error('Firebase Analytics is not initialized. Please call initializeFirebaseAnalytics first.');
        return;
    }
    firebaseAnalyticsInstance.sendEvent(eventName, eventParams);
};

// Example usage
// initializeFirebaseAnalytics('YOUR_MEASUREMENT_ID', 'YOUR_API_SECRET', 'YOUR_FIREBASE_APP_ID');
// fa_trackEvent('example_event', { param1: 'value1', param2: 'value2' });

export { initializeFirebaseAnalytics, fa_trackEvent };