import type { IUser } from "@/entities/user/types";

/**
 * Analytics Service
 *
 * Provides methods for tracking user parameters and events
 * in Yandex Metrika.
 */
export class AnalyticsService {
  private static instance: AnalyticsService;
  private user: IUser | null = null;
  private isInitialized = false;

  static getInstance(): AnalyticsService {
    if (!AnalyticsService.instance) {
      AnalyticsService.instance = new AnalyticsService();
    }
    return AnalyticsService.instance;
  }

  /**
   * Initialize analytics service with user data
   */
  async initialize(userData: IUser | null): Promise<void> {
    if (this.isInitialized) {
      return;
    }

    try {
      this.user = userData;

      // Set user parameters in analytics
      await this.setUserParameters();

      this.isInitialized = true;
    } catch {
      // Initialization failed silently
    }
  }

  /**
   * Set user parameters in Yandex Metrika
   */
  private async setUserParameters(): Promise<void> {
    if (!this.user) {
      return;
    }

    const userParams = this.extractUserParameters();

    // Set parameters in Yandex Metrika
    if (typeof window.ym === "function" && window.__YM_COUNTER_ID__) {
      try {
        window.ym(window.__YM_COUNTER_ID__, "userParams", userParams);
      } catch {
        // Failed to set user parameters silently
      }
    }
  }

  /**
   * Extract relevant user parameters for analytics
   */
  private extractUserParameters(): Record<string, unknown> {
    if (!this.user) {
      return {};
    }

    const params: Record<string, unknown> = {
      user_id: this.user._id,
      email: this.user.email,
      locale: this.user.locale,
      timezone: this.user.timezone,
      source: this.user.source,
      has_sign: this.user.sign,
      created_at: this.user.createdAt,
    };

    // Add profile information if available
    if (this.user.profile) {
      params.profile_name = this.user.profile.name;
      params.profile_gender = this.user.profile.gender;
      params.profile_age = this.user.profile.age;
      params.profile_sign = this.user.profile.sign;
      params.profile_birthdate = this.user.profile.birthdate;
    }

    // Add partner information if available
    if (this.user.partner) {
      params.partner_gender = this.user.partner.gender;
      params.partner_age = this.user.partner.age;
      params.partner_sign = this.user.partner.sign;
      params.partner_birthdate = this.user.partner.birthdate;
    }

    // Add location information if available
    if (this.user.ipLookup) {
      params.country = this.user.ipLookup.country;
      params.region = this.user.ipLookup.region;
      params.city = this.user.ipLookup.city;
      params.is_eu = this.user.ipLookup.eu;
    }

    return params;
  }

  /**
   * Track custom event in Yandex Metrika
   */
  trackEvent(eventName: string, parameters?: Record<string, unknown>): void {
    // Track in Yandex Metrika
    if (typeof window.ym === "function" && window.__YM_COUNTER_ID__) {
      try {
        window.ym(window.__YM_COUNTER_ID__, "reachGoal", eventName, parameters);
      } catch {
        // Failed to track event silently
      }
    }
  }

  /**
   * Get current user data
   */
  getUser(): IUser | null {
    return this.user;
  }

  /**
   * Check if service is initialized
   */
  isReady(): boolean {
    return this.isInitialized;
  }
}

// Export singleton instance
export const analyticsService = AnalyticsService.getInstance();
