'use client'

import { useEffect } from 'react'

export default function DetailTracker({ listingId }: { listingId: string }) {
  useEffect(() => {
    // Send fire-and-forget page view tracking event on load
    fetch('/api/events', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ listingId, actionType: 'views' })
    }).catch(err => console.error('Tracking views error:', err))

    const trackClick = (action: 'phone' | 'whatsapp' | 'menu') => {
      fetch('/api/events', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ listingId, actionType: action })
      }).catch(err => console.error(`Tracking ${action} error:`, err))
    }

    const telBtn = document.getElementById('listing-contact-phone')
    const waBtn = document.getElementById('listing-contact-whatsapp')
    const menuBtn = document.getElementById('listing-contact-menu')

    const handleTel = () => trackClick('phone')
    const handleWa = () => trackClick('whatsapp')
    const handleMenu = () => trackClick('menu')

    if (telBtn) telBtn.addEventListener('click', handleTel)
    if (waBtn) waBtn.addEventListener('click', handleWa)
    if (menuBtn) menuBtn.addEventListener('click', handleMenu)

    return () => {
      if (telBtn) telBtn.removeEventListener('click', handleTel)
      if (waBtn) waBtn.removeEventListener('click', handleWa)
      if (menuBtn) menuBtn.removeEventListener('click', handleMenu)
    }
  }, [listingId])

  return null
}
