/**
 * Analytics event tracking utility
 *
 * Supports both Google Analytics 4 (gtag) and Plausible.
 * Safe to call even when analytics is not configured — silently no-ops.
 *
 * Usage:
 *   import { trackEvent } from '../utils/analytics';
 *   trackEvent('form_submit', { form_name: 'contact' });
 */

interface EventParams {
  [key: string]: string | number | boolean;
}

/**
 * Track a custom event in GA4 and/or Plausible
 */
export function trackEvent(eventName: string, params: EventParams = {}): void {
  // Guard: skip if DNT is enabled
  if (navigator.doNotTrack === '1' || (window as any).doNotTrack === '1') {
    return;
  }

  // Google Analytics 4
  if (typeof (window as any).gtag === 'function') {
    (window as any).gtag('event', eventName, params);
  }

  // Plausible Analytics
  if (typeof (window as any).plausible === 'function') {
    (window as any).plausible(eventName, { props: params });
  }
}

/**
 * Track external link clicks
 * Call this on anchor elements pointing to external domains.
 */
export function trackExternalLink(url: string, label?: string): void {
  trackEvent('external_link_click', {
    link_url: url,
    link_label: label ?? url,
    outbound: true,
  });
}

/**
 * Track form submission events
 */
export function trackFormSubmit(formName: string, success: boolean): void {
  trackEvent(success ? 'form_submit_success' : 'form_submit_error', {
    form_name: formName,
  });
}

/**
 * Track newsletter signup events
 */
export function trackNewsletterSignup(success: boolean): void {
  trackEvent(success ? 'newsletter_signup_success' : 'newsletter_signup_error', {
    form_name: 'newsletter',
  });
}

/**
 * Track portfolio filter clicks
 */
export function trackPortfolioFilter(filter: string): void {
  trackEvent('portfolio_filter', {
    filter_category: filter,
  });
}

/**
 * Track portfolio case study views
 */
export function trackCaseStudyView(projectId: string, projectTitle: string): void {
  trackEvent('case_study_view', {
    project_id: projectId,
    project_title: projectTitle,
  });
}

/**
 * Auto-bind external link tracking to all external anchor tags on the page.
 * Call once after DOM is ready.
 */
export function bindExternalLinkTracking(): void {
  const currentHost = window.location.hostname;

  document.querySelectorAll<HTMLAnchorElement>('a[href]').forEach((anchor) => {
    try {
      const url = new URL(anchor.href, window.location.href);
      const isExternal = url.hostname !== currentHost && url.hostname !== '';

      if (isExternal) {
        anchor.addEventListener('click', () => {
          trackExternalLink(url.href, anchor.textContent?.trim() || anchor.getAttribute('aria-label') || url.href);
        });
      }
    } catch {
      // Invalid URL, skip
    }
  });
}
