"use client"

import { useEffect } from 'react'
import { usePathname } from 'next/navigation'
import { useSession } from 'next-auth/react'

// Hook para obtener o crear session ID
function useAnalyticsSessionId() {
  useEffect(() => {
    // Crear session ID si no existe
    if (typeof window !== 'undefined' && !localStorage.getItem('analytics_session_id')) {
      localStorage.setItem('analytics_session_id', crypto.randomUUID())
    }
  }, [])

  return typeof window !== 'undefined'
    ? localStorage.getItem('analytics_session_id') || crypto.randomUUID()
    : null
}

export default function AnalyticsTracker() {
  const pathname = usePathname()
  const { data: session } = useSession()
  const sessionId = useAnalyticsSessionId()

  useEffect(() => {
    // No trackear si no tenemos sessionId o si es una ruta de API
    if (!sessionId || pathname.startsWith('/api')) {
      return
    }

    // Track page visit
    const trackVisit = async () => {
      try {
        await fetch('/api/analytics/track', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userId: session?.user?.id || null,
            sessionId,
            path: pathname,
          }),
        })
      } catch (error) {
        // Silent fail - analytics no debe romper la app
        console.error('Analytics tracking failed:', error)
      }
    }

    trackVisit()
  }, [pathname, sessionId, session?.user?.id])

  // Este componente no renderiza nada
  return null
}
