import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { supabase, isSupabaseConfigured } from '../lib/supabaseClient';
import { useAuth } from '../context/AuthContext';

export const AnalyticsTracker: React.FC = () => {
  const location = useLocation();
  const { user, loading } = useAuth();

  useEffect(() => {
    // Wait for auth to initialize so we don't log "null" user then "user id" immediately after
    if (loading) return;

    const trackVisit = async () => {
      // 1. Check for cookie consent
      // If user hasn't allowed or has explicitly denied, do not track.
      const consent = localStorage.getItem('cookie_consent');
      if (consent !== 'true') {
        return;
      }

      // 2. Don't track if Supabase isn't configured (Demo mode)
      if (!isSupabaseConfigured) return;

      // 3. Check if we already logged this session
      // sessionStorage persists while the tab is open, ensuring 1 count per session
      const hasLoggedSession = sessionStorage.getItem('motionweb_visit_logged');
      
      if (hasLoggedSession) return;

      try {
        // Mark immediately to prevent race conditions if effect fires multiple times rapidly
        sessionStorage.setItem('motionweb_visit_logged', 'true');

        await supabase.from('page_visits').insert({
          page_path: location.pathname + location.hash,
          user_agent: navigator.userAgent,
          user_id: user?.id || null
        });
        
      } catch (error) {
        // Silently fail for analytics to not disrupt user experience
        console.error('Analytics tracking error:', error);
      }
    };

    trackVisit();
    
    // Add listener for storage events to re-check tracking if consent changes mid-session
    const handleStorageChange = () => trackVisit();
    window.addEventListener('storage', handleStorageChange);
    
    return () => window.removeEventListener('storage', handleStorageChange);
  }, [location, user, loading]);

  return null;
};