import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import api from '../services/api';

/**
 * Hook to track page views and user engagement
 * Automatically tracks when component mounts and route changes
 */
export const usePageTracking = (pageName?: string, metadata?: Record<string, any>) => {
  const location = useLocation();
  const hasTracked = useRef(false);

  useEffect(() => {
    // Avoid double-tracking in development (React StrictMode)
    if (hasTracked.current) return;
    hasTracked.current = true;

    const trackPageView = async () => {
      try {
        const path = location.pathname;
        const page = pageName || path;
        
        // Get session info from localStorage (or generate)
        let sessionId = localStorage.getItem('session_id');
        if (!sessionId) {
          sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
          localStorage.setItem('session_id', sessionId);
        }

        // Track the view
        await api.post('/analytics/track', {
          event_type: 'page_view',
          page_path: path,
          page_name: page,
          session_id: sessionId,
          referrer: document.referrer || null,
          user_agent: navigator.userAgent,
          screen_resolution: `${window.screen.width}x${window.screen.height}`,
          viewport_size: `${window.innerWidth}x${window.innerHeight}`,
          metadata: metadata || {},
        });
      } catch (error) {
        // Silent fail - don't break user experience if tracking fails
        console.debug('Analytics tracking failed:', error);
      }
    };

    trackPageView();

    // Reset tracking flag when location changes
    return () => {
      hasTracked.current = false;
    };
  }, [location.pathname, pageName, metadata]);
};

/**
 * Hook to track article reads with time spent
 */
export const useArticleTracking = (articleId: number | string | undefined, articleTitle?: string) => {
  const startTime = useRef(Date.now());
  const hasTracked = useRef(false);

  useEffect(() => {
    if (!articleId || hasTracked.current) return;
    hasTracked.current = true;

    const trackArticleView = async () => {
      try {
        await api.post(`/articles/${articleId}/read`, {
          title: articleTitle,
          timestamp: new Date().toISOString(),
        });
      } catch (error) {
        console.debug('Article tracking failed:', error);
      }
    };

    trackArticleView();

    // Track time spent when user leaves
    return () => {
      const timeSpent = Math.floor((Date.now() - startTime.current) / 1000);
      if (timeSpent > 5) { // Only track if spent more than 5 seconds
        api.post('/analytics/track', {
          event_type: 'article_read_time',
          article_id: articleId,
          time_spent: timeSpent,
        }).catch(() => {});
      }
    };
  }, [articleId, articleTitle]);
};

/**
 * Track custom events (clicks, downloads, etc.)
 */
export const trackEvent = async (eventType: string, eventData?: Record<string, any>) => {
  try {
    await api.post('/analytics/track', {
      event_type: eventType,
      ...eventData,
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.debug('Event tracking failed:', error);
  }
};

export default usePageTracking;
