import { Analytics, getAnalytics, logEvent, setUserProperties } from 'firebase/analytics';
import { FirebaseApp, initializeApp } from 'firebase/app';

let app: FirebaseApp;
let analytics: Analytics;

// Initialize Firebase
if (import.meta.env.VITE_ENABLE_FIREBASE === 'true') {
    console.log('Firebase 初始化开始');

    // Firebase 配置
    const firebaseConfig = {
        apiKey: 'AIzaSyCxwmQ0oUKyUi-FVdqtNZx7SE_a0Mg7xHM',
        authDomain: 'jump-visacard.firebaseapp.com',
        projectId: 'jump-visacard',
        storageBucket: 'jump-visacard.firebasestorage.app',
        messagingSenderId: '508907990485',
        appId: '1:508907990485:web:2f3bddddfc1d431224a15c',
        measurementId: 'G-G87QHZ6J4L',
    };

    app = initializeApp(firebaseConfig);
    console.log('Firebase app 已创建');

    analytics = getAnalytics(app);
    console.log('Firebase analytics 已创建');
}

/**
 * 上报自定义事件
 * @param eventName 事件名称
 * @param eventParams 事件参数
 */
export const reportEvent = (eventName: string, eventParams?: Record<string, any>) => {
    if (import.meta.env.VITE_ENABLE_FIREBASE !== 'true') {
        console.log(
            '🚫 Firebase 未启用，不上报事件, eventName:',
            eventName,
            'eventParams:',
            eventParams
        );
        return;
    }
    try {
        logEvent(analytics, eventName, eventParams);
    } catch (error) {
        console.error('Failed to report event:', error);
    }
};

/**
 * 上报错误事件
 * @param error 错误对象
 * @param errorContext 错误上下文
 */
export const reportError = (error: Error, errorContext?: Record<string, any>) => {
    if (import.meta.env.VITE_ENABLE_FIREBASE !== 'true') {
        console.log(
            '🚫 Firebase 未启用，不上报错误事件, error:',
            error,
            'errorContext:',
            errorContext
        );
        return;
    }
    try {
        logEvent(analytics, 'error', {
            error_message: error.message,
            error_stack: error.stack,
            error_name: error.name,
            ...errorContext,
        });
    } catch (e) {
        console.error('Failed to report error:', e);
    }
};

/**
 * 设置用户属性
 * @param properties 用户属性对象
 */
export const setUserPropertyValue = (properties: Record<string, string>) => {
    if (import.meta.env.VITE_ENABLE_FIREBASE !== 'true') {
        console.log('🚫 Firebase 未启用，不上报用户属性, properties:', properties);
        return;
    }
    try {
        setUserProperties(analytics, properties);
    } catch (error) {
        console.error('Failed to set user properties:', error);
    }
};

export { app, analytics };
