/**
 * Analytics Service
 * 
 * Centralized service for sending events to multiple analytics platforms:
 * - Facebook Pixel
 * - Google Analytics (GA4)
 * - Yandex Metrika
 * 
 * Page views are tracked automatically by GA4 and Yandex Metrika.
 * 
 * Usage:
 * analyticsService.trackEvent(AnalyticsEvent.ENTERED_EMAIL);
 * analyticsService.setUserId(userId);
 */

import "./types";

/**
 * Available analytics events
 */
export enum AnalyticsEvent {
  // Registration events
  ENTERED_EMAIL = "EnteredEmail",
  LEAD = "Lead", // Facebook-specific event name for EnteredEmail
}

/**
 * Analytics platforms
 */
export enum AnalyticsPlatform {
  FACEBOOK = "Facebook",
  GOOGLE_ANALYTICS = "GoogleAnalytics",
  YANDEX_METRIKA = "YandexMetrika",
}

interface EventOptions {
  [key: string]: unknown;
}

/**
 * Check if Yandex Metrika is available
 */
function isYandexMetrikaAvailable(): boolean {
  return typeof window !== "undefined" && typeof window.ym === "function";
}

/**
 * Check if Google Analytics is available
 */
function isGoogleAnalyticsAvailable(): boolean {
  return typeof window !== "undefined" && typeof window.gtag === "function";
}

/**
 * Check if Facebook Pixel is available
 */
function isFacebookPixelAvailable(): boolean {
  return typeof window !== "undefined" && typeof window.fbq === "function";
}

/**
 * Track event in Yandex Metrika
 */
function trackYandexMetrikaEvent(
  event: AnalyticsEvent,
  options?: EventOptions
): void {
  if (!isYandexMetrikaAvailable()) {
    console.warn("Yandex Metrika is not available");
    return;
  }

  // Get counter ID from the page (injected by YandexMetrika component)
  const counterId = window.__YM_COUNTER_ID__;
  if (!counterId) {
    console.warn("Yandex Metrika counter ID not found");
    return;
  }

  window.ym(counterId, "reachGoal", event, options);
  console.log(`[YM] Event: ${event}`, options);
}

/**
 * Track event in Google Analytics
 */
function trackGoogleAnalyticsEvent(
  event: AnalyticsEvent,
  options?: EventOptions
): void {
  if (!isGoogleAnalyticsAvailable()) {
    console.warn("Google Analytics is not available");
    return;
  }

  window.gtag("event", event, options);
  console.log(`[GA] Event: ${event}`, options);
}

/**
 * Track event in Facebook Pixel
 */
function trackFacebookPixelEvent(
  event: AnalyticsEvent,
  options?: EventOptions
): void {
  if (!isFacebookPixelAvailable()) {
    console.warn("Facebook Pixel is not available");
    return;
  }

  // Map EnteredEmail to Lead for Facebook
  const fbEvent = event === AnalyticsEvent.ENTERED_EMAIL ? AnalyticsEvent.LEAD : event;

  window.fbq("track", fbEvent, options);
  console.log(`[FB] Event: ${fbEvent}`, options);
}

/**
 * Track event across multiple platforms
 * 
 * @param event - Event to track
 * @param platforms - Platforms to send event to (defaults to all available)
 * @param options - Additional event data
 */
export function trackEvent(
  event: AnalyticsEvent,
  platforms?: AnalyticsPlatform[],
  options?: EventOptions
): void {
  // If no platforms specified, send to all available
  const targetPlatforms = platforms || [
    AnalyticsPlatform.FACEBOOK,
    AnalyticsPlatform.GOOGLE_ANALYTICS,
    AnalyticsPlatform.YANDEX_METRIKA,
  ];

  targetPlatforms.forEach((platform) => {
    switch (platform) {
      case AnalyticsPlatform.YANDEX_METRIKA:
        trackYandexMetrikaEvent(event, options);
        break;
      case AnalyticsPlatform.GOOGLE_ANALYTICS:
        trackGoogleAnalyticsEvent(event, options);
        break;
      case AnalyticsPlatform.FACEBOOK:
        trackFacebookPixelEvent(event, options);
        break;
    }
  });
}

/**
 * Set user ID across all analytics platforms
 */
export function setUserId(userId: string): void {
  // Yandex Metrika
  if (isYandexMetrikaAvailable()) {
    const counterId = window.__YM_COUNTER_ID__;
    if (counterId) {
      window.ym(counterId, "setUserID", userId);
      console.log(`[YM] User ID set: ${userId}`);
    }
  }

  // Google Analytics - set user_id property for all subsequent events
  if (isGoogleAnalyticsAvailable()) {
    window.gtag("set", { user_id: userId });
    console.log(`[GA] User ID set: ${userId}`);
  }
}

/**
 * Set user properties/parameters
 */
export function setUserProperties(properties: Record<string, unknown>): void {
  // Yandex Metrika
  if (isYandexMetrikaAvailable()) {
    const counterId = window.__YM_COUNTER_ID__;
    if (counterId) {
      window.ym(counterId, "userParams", properties);
      console.log(`[YM] User params set:`, properties);
    }
  }

  // Google Analytics
  if (isGoogleAnalyticsAvailable()) {
    window.gtag("set", "user_properties", properties);
    console.log(`[GA] User properties set:`, properties);
  }
}

const analyticsService = {
  trackEvent,
  setUserId,
  setUserProperties,
  AnalyticsEvent,
  AnalyticsPlatform,
};

export default analyticsService;
