export function generateClickRef(): string {
  const ts = Math.floor(Date.now() / 1000).toString(16);
  const rand = Math.random().toString(36).substring(2, 8);
  return `sp_${ts}_${rand}`;
}

export function getPageSource(): string {
  if (typeof window === 'undefined') return 'server';
  const path = window.location.pathname;
  if (path === '/') return 'homepage';
  if (path.startsWith('/zoeken')) return 'search';
  if (path.startsWith('/deals')) return 'deals';
  if (path.startsWith('/sneaker/') || path.startsWith('/sneakers/')) return 'pdp';
  if (path.startsWith('/collectie/')) return 'collection';
  return 'other';
}

export async function trackClick(params: {
  product_id: string;
  shop_id: string;
  offer_id?: string;
  source?: string;
  source_detail?: string;
  position?: number;
}): Promise<{ redirect_url: string } | null> {
  try {
    const res = await fetch('/api/track/click', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...params,
        source: params.source || getPageSource(),
      }),
    });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

export async function trackPageView(params: {
  product_id?: string;
  page_type?: string;
}): Promise<void> {
  try {
    await fetch('/api/track/view', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        product_id: params.product_id || null,
        page_type: params.page_type || getPageSource(),
      }),
    });
  } catch {}
}

export function hashIP(ip: string): string {
  // Simple hash for privacy - in production use crypto
  let hash = 0;
  for (let i = 0; i < ip.length; i++) {
    const char = ip.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash |= 0;
  }
  return hash.toString(16);
}
