import { GA4Provider } from './providers/GA4Provider';
import { NoopProvider } from './providers/NoopProvider';
import { networkDetector } from './NetworkDetector';
import { updateGoogleConsent } from './googleConsentMode';

export class AnalyticsManager {
  constructor(config = {}) {
    this.provider = this.createProvider(config);
    this.networkDetector = networkDetector;
    this.config = config;
    this.consentLocked = false;
  }

  createProvider(config) {
    const providerType = config.providerType || 'noop';

    switch (providerType) {
      case 'ga4':
        return new GA4Provider({
          measurementId: config.measurementId,
          hasConsent: config.hasConsent,
          debugMode: config.debugMode,
        });
      case 'noop':
      default:
        return new NoopProvider();
    }
  }

  async initialize() {
    if (!this.networkDetector.getStatus()) {
      console.log('AnalyticsManager: offline, skipping initialization');
      return;
    }

    await this.provider.initialize();
  }

  trackPageView(data) {
    if (!this.networkDetector.getStatus()) return;
    this.provider.trackPageView(data);
  }

  trackEvent(eventName, eventData) {
    if (!this.networkDetector.getStatus()) return;

    this.provider.trackEvent(eventName, eventData);
  }

  setUserId(userId) {
    this.provider.setUserId(userId);
  }

  setConsentGranted(hasConsent) {
    updateGoogleConsent(hasConsent);

    if (this.provider.setConsentGranted) {
      this.provider.setConsentGranted(hasConsent);
    }
  }

  _setConsentGrantedInternal(hasConsent) {
    this.setConsentGranted(hasConsent);
    this.consentLocked = true;
    if (this.provider._lockConsent) {
      this.provider._lockConsent();
    }
  }
}

let instance = null;

export function initializeAnalytics(config) {
  instance = new AnalyticsManager(config);
  // Initialize provider (load GA4 script, etc)
  instance.initialize().catch(err => {
    console.error('❌ Failed to initialize analytics:', err);
  });
  // Expose globally for testing only in development
  if (import.meta.env.DEV) {
    window.__ANALYTICS__ = instance;
    window.__getAnalytics__ = getAnalytics;
  }
  return instance;
}

export function getAnalytics() {
  if (!instance) {
    console.warn('⚠️ Analytics not initialized, creating NoopProvider');
    instance = new AnalyticsManager({ providerType: 'noop' });
    if (import.meta.env.DEV) {
      window.__ANALYTICS__ = instance;
    }
  }
  return instance;
}
