import React from 'react';

// Analytics Utility for User Behavior Tracking
// Plausible Analytics entegrasyonu için hazır yapı

export interface AnalyticsEvent {
  name: string;
  props?: Record<string, string | number | boolean>;
}

export interface PageViewEvent {
  url: string;
  referrer?: string;
  props?: Record<string, string | number | boolean>;
}

class Analytics {
  private isEnabled = false;
  private domain: string;

  constructor() {
    this.domain = window.location.hostname;
    this.initPlausible();
  }

  private initPlausible() {
    // Plausible Analytics script'i yüklü mü kontrol et
    if (typeof window !== 'undefined' && (window as any).plausible) {
      this.isEnabled = true;
    }
  }

  /**
   * Sayfa görüntüleme olayını izle
   */
  trackPageView(url?: string, props?: Record<string, string | number | boolean>) {
    if (!this.isEnabled) return;

    const pageUrl = url || window.location.pathname + window.location.search;

    try {
      (window as any).plausible('pageview', {
        u: pageUrl,
        props,
      });
    } catch (error) {
      console.error('Analytics pageview hatası:', error);
    }
  }

  /**
   * Özel olay izle
   */
  trackEvent(eventName: string, props?: Record<string, string | number | boolean>) {
    if (!this.isEnabled) {
      // Development'ta console'a yaz
      if (import.meta.env.DEV) {
        console.log('[Analytics Event]', eventName, props);
      }
      return;
    }

    try {
      (window as any).plausible(eventName, { props });
    } catch (error) {
      console.error('Analytics event hatası:', error);
    }
  }

  /**
   * Conversion funnel tracking
   */
  trackFunnelStep(funnelName: string, step: string, props?: Record<string, any>) {
    this.trackEvent(`${funnelName}_${step}`, {
      funnel: funnelName,
      step,
      ...props,
    });
  }

  /**
   * User action tracking
   */
  trackUserAction(action: string, category: string, props?: Record<string, any>) {
    this.trackEvent('user_action', {
      action,
      category,
      ...props,
    });
  }

  /**
   * Error tracking
   */
  trackError(errorType: string, errorMessage: string, props?: Record<string, any>) {
    this.trackEvent('error', {
      error_type: errorType,
      error_message: errorMessage,
      ...props,
    });
  }

  /**
   * Performance tracking
   */
  trackPerformance(metric: string, value: number, unit: string = 'ms') {
    this.trackEvent('performance', {
      metric,
      value,
      unit,
    });
  }
}

// Singleton instance
export const analytics = new Analytics();

// Predefined event tracking functions

/**
 * Trip creation funnel
 */
export const trackTripCreationFunnel = {
  started: () => analytics.trackFunnelStep('trip_creation', 'started'),
  destinationSelected: (destination: string) =>
    analytics.trackFunnelStep('trip_creation', 'destination_selected', { destination }),
  datesSelected: (duration: number) =>
    analytics.trackFunnelStep('trip_creation', 'dates_selected', { duration }),
  interestsSelected: (interests: string[]) =>
    analytics.trackFunnelStep('trip_creation', 'interests_selected', {
      interests: interests.join(','),
      count: interests.length,
    }),
  completed: (tripId: string) =>
    analytics.trackFunnelStep('trip_creation', 'completed', { trip_id: tripId }),
  abandoned: (step: string) =>
    analytics.trackFunnelStep('trip_creation', 'abandoned', { step }),
};

/**
 * Trip planning actions
 */
export const trackTripPlanning = {
  placeAdded: (placeType: string) =>
    analytics.trackUserAction('place_added', 'trip_planning', { place_type: placeType }),
  placeRemoved: (placeType: string) =>
    analytics.trackUserAction('place_removed', 'trip_planning', { place_type: placeType }),
  placeReordered: () => analytics.trackUserAction('place_reordered', 'trip_planning'),
  aiSuggestionUsed: (suggestionType: string) =>
    analytics.trackUserAction('ai_suggestion_used', 'trip_planning', {
      suggestion_type: suggestionType,
    }),
  tripShared: (shareMethod: string) =>
    analytics.trackUserAction('trip_shared', 'trip_planning', { share_method: shareMethod }),
};

/**
 * Provider interactions
 */
export const trackProviderInteractions = {
  providerViewed: (providerId: string) =>
    analytics.trackUserAction('provider_viewed', 'provider', { provider_id: providerId }),
  leadCreated: (providerId: string, tourType: string) =>
    analytics.trackUserAction('lead_created', 'provider', {
      provider_id: providerId,
      tour_type: tourType,
    }),
  contactClicked: (providerId: string) =>
    analytics.trackUserAction('contact_clicked', 'provider', { provider_id: providerId }),
};

/**
 * User engagement
 */
export const trackEngagement = {
  searchPerformed: (query: string, resultsCount: number) =>
    analytics.trackUserAction('search_performed', 'engagement', {
      query_length: query.length,
      results_count: resultsCount,
    }),
  filterApplied: (filterType: string, filterValue: string) =>
    analytics.trackUserAction('filter_applied', 'engagement', {
      filter_type: filterType,
      filter_value: filterValue,
    }),
  bookmarkAdded: (itemType: string) =>
    analytics.trackUserAction('bookmark_added', 'engagement', { item_type: itemType }),
  bookmarkRemoved: (itemType: string) =>
    analytics.trackUserAction('bookmark_removed', 'engagement', { item_type: itemType }),
};

/**
 * Auth events
 */
export const trackAuth = {
  signupStarted: () => analytics.trackFunnelStep('signup', 'started'),
  signupCompleted: (method: string) =>
    analytics.trackFunnelStep('signup', 'completed', { method }),
  loginCompleted: (method: string) => analytics.trackEvent('login', { method }),
  logoutCompleted: () => analytics.trackEvent('logout'),
};

/**
 * GDPR events
 */
export const trackGDPR = {
  consentGiven: (consentType: string) =>
    analytics.trackEvent('consent_given', { consent_type: consentType }),
  consentRevoked: (consentType: string) =>
    analytics.trackEvent('consent_revoked', { consent_type: consentType }),
  dataExportRequested: () => analytics.trackEvent('data_export_requested'),
  accountDeletionRequested: () => analytics.trackEvent('account_deletion_requested'),
};

/**
 * Performance metrics
 */
export const trackPerformanceMetrics = {
  pageLoadTime: (duration: number) => analytics.trackPerformance('page_load_time', duration),
  apiResponseTime: (endpoint: string, duration: number) =>
    analytics.trackPerformance('api_response_time', duration, 'ms'),
  componentRenderTime: (componentName: string, duration: number) =>
    analytics.trackPerformance('component_render_time', duration, 'ms'),
};

// React hook for page view tracking
export function usePageTracking() {
  React.useEffect(() => {
    analytics.trackPageView();
  }, []);
}

export default analytics;
