const API_URL = process.env.NEXT_PUBLIC_API_URL || '/api';

function getSessionId(): string {
  if (typeof window === 'undefined') return '';
  let sid = sessionStorage.getItem('sc_session_id');
  if (!sid) {
    sid = `s_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
    sessionStorage.setItem('sc_session_id', sid);
  }
  return sid;
}

export function getVisitorId(): string {
  if (typeof window === 'undefined') return '';
  let vid = localStorage.getItem('sc_visitor_id');
  if (!vid) {
    vid = `v_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
    localStorage.setItem('sc_visitor_id', vid);
  }
  return vid;
}

function beacon(url: string, body: Record<string, any>) {
  try {
    const payload = JSON.stringify(body);
    if (navigator.sendBeacon) {
      navigator.sendBeacon(url, new Blob([payload], { type: 'application/json' }));
    } else {
      fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload, keepalive: true }).catch(() => {});
    }
  } catch { /* silent */ }
}

export function trackPageview(path: string) {
  if (typeof window === 'undefined') return;
  beacon(`${API_URL}/pageviews/track`, {
    path,
    referrer: document.referrer || '',
    visitor_id: getVisitorId(),
    session_id: getSessionId(),
    screen_w: window.innerWidth,
  });
}

export function trackConversion(event: string, data?: Record<string, any>) {
  if (typeof window === 'undefined') return;
  beacon(`${API_URL}/pageviews/conversion`, {
    event,
    visitor_id: getVisitorId(),
    session_id: getSessionId(),
    data: data || {},
  });
}
