'use client'

import { useEffect, useRef } from 'react'

export function useVisitorTracking() {
  const tracked = useRef(false)

  useEffect(() => {
    // Only track once per page load
    if (tracked.current) return
    tracked.current = true

    const trackVisitor = async () => {
      try {
        // Get current page path
        const path = window.location.pathname

        // Track visitor without waiting for response
        fetch('/api/visitors', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ path }),
        }).catch(() => {
          // Silently fail - tracking shouldn't break the app
          console.log('Visitor tracking failed (silent)')
        })
      } catch (error) {
        // Silently fail
        console.log('Visitor tracking error (silent)')
      }
    }

    // Track immediately
    trackVisitor()

    // Optional: Track again after 30 minutes if still on page
    const interval = setInterval(() => {
      tracked.current = false // Reset flag to allow re-tracking
      trackVisitor()
    }, 30 * 60 * 1000) // 30 minutes

    return () => clearInterval(interval)
  }, [])
}