/**
 * Analytics Service - Wrapper around Google Analytics (gtag.js)
 * Provides typed, consistent event tracking throughout the application
 * Follows LOTR-themed naming conventions
 */

// Declare gtag function from window
declare function gtag(...args: any[]): void;

/**
 * Event names for Fellowship's Quest - LOTR themed
 */
export const AnalyticsEvents = {
  // Authentication
  USER_SIGNUP: 'user_signup',
  USER_LOGIN: 'user_login',
  USER_LOGOUT: 'user_logout',
  
  // Quests
  QUEST_CREATED: 'quest_created',
  QUEST_UPDATED: 'quest_updated',
  QUEST_DELETED: 'quest_deleted',
  QUEST_COMPLETED: 'quest_completed',
  
  // Games/Mini-games
  GAME_STARTED: 'game_started',
  GAME_COMPLETED: 'game_completed',
  GAME_FAILED: 'game_failed',
  
  // Bargaining/Shop
  BARGAIN_INITIATED: 'bargain_initiated',
  BARGAIN_COMPLETED: 'bargain_completed',
  BARGAIN_FAILED: 'bargain_failed',
  ITEM_PURCHASED: 'item_purchased',
  
  // Chat/NPC Interactions
  NPC_CHAT_INITIATED: 'npc_chat_initiated',
  NPC_MESSAGE_SENT: 'npc_message_sent',
  
  // Inventory
  INVENTORY_VIEWED: 'inventory_viewed',
  INVENTORY_ITEM_ADDED: 'inventory_item_added',
  INVENTORY_ITEM_REMOVED: 'inventory_item_removed',
  
  // Navigation
  PAGE_VIEWED: 'page_view',
  MAP_VIEWED: 'map_viewed',
  DASHBOARD_VIEWED: 'dashboard_viewed',
  QUESTS_PAGE_VIEWED: 'quests_page_viewed',
} as const;

/**
 * User property names for Fellowship's Quest custom dimensions
 */
export const AnalyticsUserProperties = {
  CHARACTER_NAME: 'character_name',
  USER_TYPE: 'user_type', // 'fellowship_member' or 'guest'
  FELLOWSHIP_MEMBER: 'fellowship_member', // Name of Fellowship member (Frodo, Sam, etc.)
  SIGNUP_DATE: 'signup_date',
} as const;

/**
 * Analytics Service - Main interface for event tracking
 */
class AnalyticsService {
  private isEnabled: boolean = true;

  constructor() {
    // Check if gtag is available
    this.isEnabled = typeof window !== 'undefined' && typeof (window as any).gtag === 'function';
    
    // Disable analytics in test environments or when explicitly requested
    const isAnalyticsDisabled =
      process.env.REACT_APP_DISABLE_ANALYTICS === 'true' ||
      (typeof window !== 'undefined' && (
        // Playwright/Cypress/E2E detection
        ((window as any).Cypress !== undefined) ||
        // Selenium/WebDriver detection
        (navigator.webdriver === true)
      ));
    
    // Update isEnabled based on test environment detection
    if (isAnalyticsDisabled) {
      this.isEnabled = false;
    }
  }

  /**
   * Track a user event with custom parameters
   */
  trackEvent(
    eventName: string,
    parameters?: Record<string, string | number | boolean>
  ): void {
      if (!this.isEnabled) {
      console.debug('Analytics disabled or gtag not available');
      return;
    }

    try {
      gtag('event', eventName, parameters || {});
    } catch (error) {
      console.error('Error tracking analytics event:', error);
    }
  }

  /**
   * Set user properties for the current session
   */
  setUserProperties(properties: Record<string, string | number | boolean>): void {
    if (!this.isEnabled) {
      console.debug('Analytics disabled or gtag not available');
      return;
    }

    try {
      gtag('config', {
        ...properties,
      });
    } catch (error) {
      console.error('Error setting user properties:', error);
    }
  }

  /**
   * Set user ID for cross-device tracking (requires consent)
   */
  setUserId(userId: string | number): void {
    if (!this.isEnabled) {
      console.debug('Analytics disabled or gtag not available');
      return;
    }

    try {
      gtag('config', {
        'user_id': String(userId),
      });
    } catch (error) {
      console.error('Error setting user ID:', error);
    }
  }

  // ==================== Authentication Events ====================

  /**
   * Track user signup event
   */
  trackSignup(username: string): void {
    this.trackEvent(AnalyticsEvents.USER_SIGNUP, {
      username: username,
    });
  }

  /**
   * Track user login event
   */
  trackLogin(username: string): void {
    this.trackEvent(AnalyticsEvents.USER_LOGIN, {
      username: username,
    });
  }

  /**
   * Track user logout event
   */
  trackLogout(): void {
    this.trackEvent(AnalyticsEvents.USER_LOGOUT);
  }

  // ==================== Quest Events ====================

  /**
   * Track quest creation
   */
  trackQuestCreated(questId: number, questTitle: string, questType?: string): void {
    this.trackEvent(AnalyticsEvents.QUEST_CREATED, {
      quest_id: questId,
      quest_title: questTitle,
      quest_type: questType || 'unknown',
    });
  }

  /**
   * Track quest update/modification
   */
  trackQuestUpdated(questId: number, questTitle: string): void {
    this.trackEvent(AnalyticsEvents.QUEST_UPDATED, {
      quest_id: questId,
      quest_title: questTitle,
    });
  }

  /**
   * Track quest deletion
   */
  trackQuestDeleted(questId: number, questTitle: string): void {
    this.trackEvent(AnalyticsEvents.QUEST_DELETED, {
      quest_id: questId,
      quest_title: questTitle,
    });
  }

  /**
   * Track quest completion (after successful mini-game)
   */
  trackQuestCompleted(questId: number, questTitle: string, gameType?: string): void {
    this.trackEvent(AnalyticsEvents.QUEST_COMPLETED, {
      quest_id: questId,
      quest_title: questTitle,
      game_type: gameType || 'unknown',
    });
  }

  // ==================== Game Events ====================

  /**
   * Track game/mini-game started
   */
  trackGameStarted(gameType: string): void {
    this.trackEvent(AnalyticsEvents.GAME_STARTED, {
      game_type: gameType,
    });
  }

  /**
   * Track game/mini-game completed successfully
   */
  trackGameCompleted(gameType: string, score?: number): void {
    this.trackEvent(AnalyticsEvents.GAME_COMPLETED, {
      game_type: gameType,
      score: score || 0,
    });
  }

  /**
   * Track game/mini-game failed
   */
  trackGameFailed(gameType: string, reason?: string): void {
    this.trackEvent(AnalyticsEvents.GAME_FAILED, {
      game_type: gameType,
      reason: reason || 'unknown',
    });
  }

  // ==================== Bargaining/Shop Events ====================

  /**
   * Track bargaining session initiated
   */
  trackBargainInitiated(): void {
    this.trackEvent(AnalyticsEvents.BARGAIN_INITIATED);
  }

  /**
   * Track bargain/negotiation completed successfully
   */
  trackBargainCompleted(itemName: string, bargainValue?: number): void {
    this.trackEvent(AnalyticsEvents.BARGAIN_COMPLETED, {
      item_name: itemName,
      bargain_value: bargainValue || 0,
    });
  }

  /**
   * Track failed bargain/negotiation
   */
  trackBargainFailed(itemName?: string): void {
    this.trackEvent(AnalyticsEvents.BARGAIN_FAILED, {
      item_name: itemName || 'unknown',
    });
  }

  /**
   * Track item purchased (from shop/bargaining)
   */
  trackItemPurchased(itemName: string, price: number, itemId?: number): void {
    this.trackEvent(AnalyticsEvents.ITEM_PURCHASED, {
      item_name: itemName,
      item_id: itemId || 0,
      price: price,
      currency: 'gold', // LOTR-themed currency
    });
  }

  // ==================== NPC Chat Events ====================

  /**
   * Track NPC chat session initiated
   */
  trackNpcChatInitiated(character: string): void {
    this.trackEvent(AnalyticsEvents.NPC_CHAT_INITIATED, {
      character: character,
    });
  }

  /**
   * Track NPC message sent by user
   */
  trackNpcMessageSent(character: string, messageLength?: number): void {
    this.trackEvent(AnalyticsEvents.NPC_MESSAGE_SENT, {
      character: character,
      message_length: messageLength || 0,
    });
  }

  // ==================== Inventory Events ====================

  /**
   * Track inventory page viewed
   */
  trackInventoryViewed(itemCount?: number): void {
    this.trackEvent(AnalyticsEvents.INVENTORY_VIEWED, {
      item_count: itemCount || 0,
    });
  }

  /**
   * Track item added to inventory
   */
  trackInventoryItemAdded(itemName: string, quantity?: number): void {
    this.trackEvent(AnalyticsEvents.INVENTORY_ITEM_ADDED, {
      item_name: itemName,
      quantity: quantity || 1,
    });
  }

  /**
   * Track item removed from inventory
   */
  trackInventoryItemRemoved(itemName: string, quantity?: number): void {
    this.trackEvent(AnalyticsEvents.INVENTORY_ITEM_REMOVED, {
      item_name: itemName,
      quantity: quantity || 1,
    });
  }

  // ==================== Navigation Events ====================

  /**
   * Track page/view navigation
   */
  trackPageView(pageName: string, pageTitle?: string): void {
    this.trackEvent('page_view', {
      page_title: pageTitle || pageName,
      page_location: window.location.href,
    });
  }

  /**
   * Track map page viewed
   */
  trackMapViewed(): void {
    this.trackEvent(AnalyticsEvents.MAP_VIEWED, {
      page_title: 'Middle-earth Map',
    });
  }

  /**
   * Track dashboard viewed
   */
  trackDashboardViewed(): void {
    this.trackEvent(AnalyticsEvents.DASHBOARD_VIEWED, {
      page_title: 'The Council Chamber',
    });
  }

  /**
   * Track quests page viewed
   */
  trackQuestsPageViewed(): void {
    this.trackEvent(AnalyticsEvents.QUESTS_PAGE_VIEWED, {
      page_title: 'Quests',
    });
  }

  // ==================== Utility Methods ====================

  /**
   * Check if analytics is enabled
   */
  isAnalyticsEnabled(): boolean {
    return this.isEnabled;
  }

  /**
   * Enable/disable analytics tracking (for consent management)
   */
  setEnabled(enabled: boolean): void {
    this.isEnabled = enabled;
  }
}

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

export default analyticsService;
