'use client';

import { useEffect } from 'react';

type ClickType = 'amsoil' | 'internal' | 'social' | 'external';

/**
 * Categorize a link by its destination
 */
function categorizeLink(href: string, currentHost: string): ClickType {
  // AMSOIL store links
  if (href.includes('amsoil.com')) {
    return 'amsoil';
  }

  // Internal links (same domain or relative paths)
  if (href.startsWith('/') || href.startsWith('#') || href.includes(currentHost)) {
    return 'internal';
  }

  // Social media links
  const socialPatterns = [
    'facebook.com',
    'fb.com',
    'twitter.com',
    'x.com',
    'instagram.com',
    'linkedin.com',
    'youtube.com',
    'youtu.be',
    'tiktok.com',
    'pinterest.com',
  ];
  if (socialPatterns.some((pattern) => href.includes(pattern))) {
    return 'social';
  }

  // Everything else is external
  return 'external';
}

/**
 * ClickTracker component - tracks all link clicks on dealer pages
 *
 * Include this component in the dealer page layout to enable click tracking.
 * Uses navigator.sendBeacon for reliable, non-blocking tracking even during navigation.
 */
export function ClickTracker() {
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      // Find the closest anchor element
      const link = (e.target as Element).closest('a[href]') as HTMLAnchorElement | null;
      if (!link) return;

      const href = link.getAttribute('href');
      if (!href) return;

      // Skip javascript: links and empty hrefs
      if (href.startsWith('javascript:') || href === '#') return;

      const clickType = categorizeLink(href, window.location.host);

      // Use sendBeacon for reliable delivery during page navigation
      const data = JSON.stringify({
        type: 'click',
        sourcePath: window.location.pathname,
        targetHref: href,
        clickType,
      });

      // sendBeacon is designed for this use case - fires reliably even during unload
      navigator.sendBeacon('/api/stats/events', data);
    };

    // Use capture phase to catch clicks before they might be stopped
    document.addEventListener('click', handler, { capture: true });

    return () => {
      document.removeEventListener('click', handler, { capture: true });
    };
  }, []);

  // This component doesn't render anything
  return null;
}

export default ClickTracker;
