'use client';

import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

// Generate a simple session ID
const generateSessionId = (): string => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

// Get or create session ID
const getSessionId = (): string => {
  if (typeof window === 'undefined') return '';

  let sessionId = sessionStorage.getItem('visitor_session_id');
  if (!sessionId) {
    sessionId = generateSessionId();
    sessionStorage.setItem('visitor_session_id', sessionId);
  }
  return sessionId;
};

// Extract UTM parameters from URL
const getUtmParams = () => {
  if (typeof window === 'undefined') return {};

  const params = new URLSearchParams(window.location.search);
  return {
    utm_source: params.get('utm_source') || undefined,
    utm_medium: params.get('utm_medium') || undefined,
    utm_campaign: params.get('utm_campaign') || undefined,
  };
};

export function useVisitorTracking() {
  const pathname = usePathname();
  const lastPath = useRef<string>('');

  useEffect(() => {
    // Avoid duplicate tracking on same path
    if (pathname === lastPath.current) return;
    lastPath.current = pathname;

    // Skip admin pages from tracking
    if (pathname.startsWith('/admin')) return;

    const trackVisit = async () => {
      try {
        const token = localStorage.getItem('token');
        const headers: Record<string, string> = {
          'Content-Type': 'application/json',
        };
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }

        const utmParams = getUtmParams();

        await fetch(`${API_URL}/api/visitor/log`, {
          method: 'POST',
          headers,
          body: JSON.stringify({
            page_path: pathname,
            page_title: document.title,
            referrer: document.referrer || null,
            session_id: getSessionId(),
            ...utmParams,
          }),
        });
      } catch (error) {
        // Silent fail - don't disrupt user experience
        console.debug('Visitor tracking failed:', error);
      }
    };

    // Small delay to ensure page title is set
    setTimeout(trackVisit, 100);
  }, [pathname]);
}

// Component wrapper for use in layout
export function VisitorTracker() {
  useVisitorTracking();
  return null;
}
