← back to Watches

analytics/analytics-integration.js

376 lines

/**
 * Analytics Integration for Main Application
 * Integrates GA4, Funnel Tracking, Cohort Analysis, and A/B Testing
 */

// This file should be included in the main app HTML
(function() {
  'use strict';

  // Configuration
  const CONFIG = {
    GA4_MEASUREMENT_ID: 'G-XXXXXXXXXX', // Replace with actual GA4 ID
    ANALYTICS_SERVER: 'http://45.61.58.125:7650',
    ENABLE_GA4: true,
    ENABLE_BACKEND: true,
    DEBUG: true
  };

  // Initialize analytics components
  let analytics = null;
  let funnelTracker = null;
  let cohortAnalyzer = null;
  let abTesting = null;

  /**
   * Initialize all analytics systems
   */
  async function initializeAnalytics() {
    try {
      // Initialize GA4
      if (CONFIG.ENABLE_GA4 && typeof GA4Analytics !== 'undefined') {
        analytics = new GA4Analytics(CONFIG.GA4_MEASUREMENT_ID);
        await analytics.initialize();
        analytics.startEngagementTracking();
        log('GA4 Analytics initialized');
      }

      // Initialize Funnel Tracker
      if (typeof FunnelTracker !== 'undefined') {
        funnelTracker = new FunnelTracker(analytics || createDummyAnalytics());
        log('Funnel Tracker initialized');
      }

      // Initialize Cohort Analyzer
      if (typeof CohortAnalyzer !== 'undefined') {
        cohortAnalyzer = new CohortAnalyzer(analytics || createDummyAnalytics());
        log('Cohort Analyzer initialized');
      }

      // Initialize A/B Testing
      if (typeof ABTestingFramework !== 'undefined') {
        abTesting = new ABTestingFramework(analytics || createDummyAnalytics());
        log('A/B Testing Framework initialized');
      }

      // Setup watch-specific tracking
      setupWatchTracking();

      // Setup automatic tracking
      setupAutomaticTracking();

      log('All analytics systems initialized successfully');
    } catch (error) {
      console.error('Failed to initialize analytics:', error);
    }
  }

  /**
   * Create dummy analytics object if GA4 not available
   */
  function createDummyAnalytics() {
    return {
      trackEvent: (name, params) => log('Event:', name, params),
      userId: 'anonymous',
      sessionId: 'session_' + Date.now()
    };
  }

  /**
   * Setup watch-specific tracking
   */
  function setupWatchTracking() {
    // Track watch views
    window.trackWatchView = function(watch) {
      if (analytics) {
        analytics.trackWatchView(watch);
      }

      if (cohortAnalyzer) {
        cohortAnalyzer.recordAction('watch_view', {
          watch_id: watch.id,
          watch_series: watch.series
        });
      }

      if (funnelTracker) {
        funnelTracker.trackStep('watch_discovery', 'view_details', {
          watch_id: watch.id
        });
      }
    };

    // Track watch comparison
    window.trackWatchComparison = function(watches) {
      if (analytics) {
        analytics.trackWatchComparison(watches);
      }

      if (cohortAnalyzer) {
        cohortAnalyzer.recordAction('watch_comparison', {
          watch_count: watches.length
        });
      }

      if (funnelTracker) {
        funnelTracker.trackStep('watch_discovery', 'compare', {
          watch_count: watches.length
        });
      }

      if (abTesting) {
        abTesting.trackMetric('price_chart_layout', 'comparison_rate', 1);
      }
    };

    // Track search
    window.trackSearch = function(searchTerm, resultsCount) {
      if (analytics) {
        analytics.trackSearch(searchTerm, resultsCount);
      }

      if (funnelTracker) {
        funnelTracker.trackStep('price_research', 'search', {
          search_term: searchTerm,
          results_count: resultsCount
        });
      }

      if (abTesting) {
        const variant = abTesting.getVariant('search_algorithm');
        abTesting.trackMetric('search_algorithm', 'search_success_rate',
          resultsCount > 0 ? 1 : 0
        );
      }
    };

    // Track filter usage
    window.trackFilter = function(filterType, filterValue) {
      if (analytics) {
        analytics.trackFilter(filterType, filterValue);
      }

      if (funnelTracker) {
        funnelTracker.trackStep('collection_analysis', 'filter_series', {
          filter_type: filterType,
          filter_value: filterValue
        });
      }
    };

    // Track chart interactions
    window.trackChartInteraction = function(interactionType, details) {
      if (analytics) {
        analytics.trackChartInteraction(interactionType, details);
      }

      if (abTesting) {
        const variant = abTesting.getVariant('price_chart_layout');
        abTesting.trackMetric('price_chart_layout', 'chart_interaction_rate', 1);
      }
    };

    // Track data export
    window.trackDataExport = function(exportType) {
      if (analytics) {
        analytics.trackEvent('data_export', {
          export_type: exportType
        });
      }

      if (cohortAnalyzer) {
        cohortAnalyzer.recordAction('data_export', {
          export_type: exportType
        });
      }

      if (funnelTracker) {
        funnelTracker.trackStep('watch_discovery', 'export');
        funnelTracker.trackStep('investment_research', 'export_investment_data');
      }
    };

    // Track price predictions view
    window.trackPricePredictionView = function(watchId) {
      if (analytics) {
        analytics.trackEvent('price_prediction_view', {
          watch_id: watchId
        });
      }

      if (funnelTracker) {
        funnelTracker.trackStep('price_research', 'view_predictions', {
          watch_id: watchId
        });
        funnelTracker.trackStep('investment_research', 'view_predictions', {
          watch_id: watchId
        });
      }
    };

    // Track trending watches view
    window.trackTrendingView = function() {
      if (analytics) {
        analytics.trackEvent('trending_watches_view');
      }

      if (funnelTracker) {
        funnelTracker.trackStep('investment_research', 'view_trending');
      }
    };
  }

  /**
   * Setup automatic tracking
   */
  function setupAutomaticTracking() {
    // Track page load
    window.addEventListener('load', () => {
      if (funnelTracker) {
        funnelTracker.trackStep('watch_discovery', 'landing');
      }

      sessionStorage.setItem('page_load_time', Date.now());
    });

    // Track clicks on watch cards
    document.addEventListener('click', (event) => {
      const watchCard = event.target.closest('.watch-card');
      if (watchCard && watchCard.dataset.watchId) {
        if (abTesting) {
          const variant = abTesting.getVariant('watch_card_design');
          abTesting.trackMetric('watch_card_design', 'watch_view_rate', 1);
        }
      }

      // Track CTA button clicks
      const ctaButton = event.target.closest('.cta-button');
      if (ctaButton) {
        if (abTesting) {
          const variant = abTesting.getVariant('cta_button_color');
          abTesting.trackGoal('cta_button_color', 'cta_click', 1);
        }
      }
    });

    // Track form submissions
    document.addEventListener('submit', (event) => {
      if (analytics) {
        analytics.trackEvent('form_submit', {
          form_id: event.target.id,
          form_action: event.target.action
        });
      }
    });

    // Sync cohort data periodically
    if (cohortAnalyzer) {
      setInterval(() => {
        cohortAnalyzer.syncWithBackend();
      }, 5 * 60 * 1000); // Every 5 minutes
    }
  }

  /**
   * Apply A/B test variants
   */
  function applyABTestVariants() {
    if (!abTesting) return;

    // Price chart layout variant
    const chartVariant = abTesting.getVariant('price_chart_layout');
    if (chartVariant === 'variant_a') {
      document.body.classList.add('chart-layout-side-by-side');
    }

    // Watch card design variant
    const cardVariant = abTesting.getVariant('watch_card_design');
    if (cardVariant === 'variant_a') {
      document.body.classList.add('watch-card-enhanced');
    }

    // CTA button color variant
    const ctaVariant = abTesting.getVariant('cta_button_color');
    const ctaButtons = document.querySelectorAll('.cta-button');
    ctaButtons.forEach(button => {
      if (ctaVariant === 'variant_a') {
        button.classList.add('cta-green');
      } else if (ctaVariant === 'variant_b') {
        button.classList.add('cta-orange');
      }
    });

    log('A/B test variants applied:', {
      chart: chartVariant,
      card: cardVariant,
      cta: ctaVariant
    });
  }

  /**
   * Get analytics data
   */
  window.getAnalyticsData = function() {
    return {
      ga4: analytics ? {
        userId: analytics.userId,
        sessionId: analytics.sessionId
      } : null,
      funnels: funnelTracker ? funnelTracker.getActiveFunnels() : [],
      cohort: cohortAnalyzer ? cohortAnalyzer.getCohortMetrics() : null,
      experiments: abTesting ? abTesting.getActiveExperiments() : []
    };
  };

  /**
   * Export all analytics data
   */
  window.exportAnalyticsData = function() {
    const data = {
      ga4: analytics ? { userId: analytics.userId, sessionId: analytics.sessionId } : null,
      funnels: funnelTracker ? funnelTracker.exportFunnelData() : null,
      cohort: cohortAnalyzer ? cohortAnalyzer.exportCohortData() : null,
      experiments: abTesting ? abTesting.exportExperimentData() : null,
      timestamp: new Date().toISOString()
    };

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `analytics-export-${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  /**
   * Debug logging
   */
  function log(...args) {
    if (CONFIG.DEBUG) {
      console.log('[Analytics]', ...args);
    }
  }

  // Initialize on DOM ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAnalytics);
  } else {
    initializeAnalytics();
  }

  // Apply A/B variants after initialization
  setTimeout(applyABTestVariants, 100);

  // Expose analytics globally
  window.analyticsIntegration = {
    analytics,
    funnelTracker,
    cohortAnalyzer,
    abTesting,
    getAnalyticsData: window.getAnalyticsData,
    exportAnalyticsData: window.exportAnalyticsData
  };

})();