import Foundation
import FirebaseAnalytics
import FirebaseCore

class FirebaseService {
    static let shared = FirebaseService()

    private var isConfigured: Bool {
        FirebaseApp.app() != nil
    }

    private init() {}

    // MARK: - User Properties

    func setUserTier(_ tier: UserTier) {
        guard isConfigured else { return }
        Analytics.setUserProperty(tier.rawValue, forName: "user_tier")
    }

    enum UserTier: String {
        case free = "free"
        case premium = "premium"
    }

    // MARK: - Screen Tracking

    func logScreenView(screenName: String, screenClass: String? = nil) {
        guard isConfigured else { return }
        Analytics.logEvent(AnalyticsEventScreenView, parameters: [
            AnalyticsParameterScreenName: screenName,
            AnalyticsParameterScreenClass: screenClass ?? screenName
        ])
    }

    // MARK: - Investment Events

    func logSourceAdded(categoryName: String, sourceCount: Int) {
        guard isConfigured else { return }
        Analytics.logEvent("source_added", parameters: [
            "category_name": categoryName,
            "total_sources": sourceCount
        ])
    }

    func logSourceDeleted(categoryName: String) {
        guard isConfigured else { return }
        Analytics.logEvent("source_deleted", parameters: [
            "category_name": categoryName
        ])
    }

    func logSnapshotAdded(sourceName: String, value: Decimal) {
        guard isConfigured else { return }
        Analytics.logEvent("snapshot_added", parameters: [
            "source_name": sourceName,
            "value": NSDecimalNumber(decimal: value).doubleValue
        ])
    }

    func logCategoryCreated(name: String) {
        guard isConfigured else { return }
        Analytics.logEvent("category_created", parameters: [
            "category_name": name
        ])
    }

    // MARK: - Purchase Events

    func logPaywallShown(trigger: String) {
        guard isConfigured else { return }
        Analytics.logEvent("paywall_shown", parameters: [
            "paywall_trigger": trigger
        ])
    }

    func logPurchaseAttempt(productId: String) {
        guard isConfigured else { return }
        Analytics.logEvent("purchase_attempt", parameters: [
            "product_id": productId
        ])
    }

    func logPurchaseSuccess(productId: String, price: Decimal, isFamilyShared: Bool) {
        guard isConfigured else { return }
        Analytics.logEvent(AnalyticsEventPurchase, parameters: [
            AnalyticsParameterItemID: productId,
            AnalyticsParameterPrice: NSDecimalNumber(decimal: price).doubleValue,
            AnalyticsParameterCurrency: "EUR",
            "is_family_shared": isFamilyShared
        ])
    }

    func logPurchaseFailure(productId: String, error: String) {
        guard isConfigured else { return }
        Analytics.logEvent("purchase_failed", parameters: [
            "product_id": productId,
            "error": error
        ])
    }

    func logRestorePurchases(success: Bool) {
        guard isConfigured else { return }
        Analytics.logEvent("restore_purchases", parameters: [
            "success": success
        ])
    }

    // MARK: - Feature Usage Events

    func logChartViewed(chartType: String, isPremium: Bool) {
        guard isConfigured else { return }
        Analytics.logEvent("chart_viewed", parameters: [
            "chart_type": chartType,
            "is_premium_chart": isPremium
        ])
    }

    func logPredictionViewed(algorithm: String) {
        guard isConfigured else { return }
        Analytics.logEvent("prediction_viewed", parameters: [
            "algorithm": algorithm
        ])
    }

    func logExportAttempt(format: String, success: Bool) {
        guard isConfigured else { return }
        Analytics.logEvent("export_attempt", parameters: [
            "format": format,
            "success": success
        ])
    }

    func logNotificationScheduled(frequency: String) {
        guard isConfigured else { return }
        Analytics.logEvent("notification_scheduled", parameters: [
            "frequency": frequency
        ])
    }

    // MARK: - Ad Events

    func logAdImpression(adType: String) {
        guard isConfigured else { return }
        Analytics.logEvent("ad_impression", parameters: [
            "ad_type": adType
        ])
    }

    func logAdClick(adType: String) {
        guard isConfigured else { return }
        Analytics.logEvent("ad_click", parameters: [
            "ad_type": adType
        ])
    }

    // MARK: - Engagement Events

    func logOnboardingCompleted(stepCount: Int) {
        guard isConfigured else { return }
        Analytics.logEvent("onboarding_completed", parameters: [
            "steps_completed": stepCount
        ])
    }

    /// Per-step onboarding funnel event — lets us see exactly where users drop off
    /// inside onboarding (only the final `onboarding_completed` existed before).
    func logOnboardingStep(step: Int) {
        guard isConfigured else { return }
        Analytics.logEvent("onboarding_step", parameters: [
            "step": step
        ])
    }

    func logOnboardingSkipped(atStep step: Int) {
        guard isConfigured else { return }
        Analytics.logEvent("onboarding_skipped", parameters: [
            "step": step
        ])
    }

    /// Viral loop measurement: fired whenever the user opens a share sheet with
    /// app content (portfolio image, check-in, goal). `type` identifies the surface.
    func logShare(type: String) {
        guard isConfigured else { return }
        Analytics.logEvent("content_shared", parameters: [
            "share_type": type
        ])
    }

    func logWidgetUsed(widgetType: String) {
        guard isConfigured else { return }
        Analytics.logEvent("widget_used", parameters: [
            "widget_type": widgetType
        ])
    }

    func logAppOpened(fromWidget: Bool) {
        guard isConfigured else { return }
        Analytics.logEvent("app_opened", parameters: [
            "from_widget": fromWidget
        ])
    }

    // MARK: - Portfolio Events

    func logPortfolioMilestone(totalValue: Decimal, milestone: String) {
        guard isConfigured else { return }
        Analytics.logEvent("portfolio_milestone", parameters: [
            "total_value": NSDecimalNumber(decimal: totalValue).doubleValue,
            "milestone": milestone
        ])
    }

    // MARK: - Error Events

    func logError(type: String, message: String, context: String? = nil) {
        guard isConfigured else { return }
        Analytics.logEvent("app_error", parameters: [
            "error_type": type,
            "error_message": message,
            "context": context ?? ""
        ])
    }
}

