// Google Analytics & Vercel Analytics Integration

// Initialize Google Analytics
export const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID

declare global {
  interface Window {
    gtag?: (
      command: string,
      targetId: string,
      config?: Record<string, any>
    ) => void
  }
}

// Page view tracking
export const pageview = (url: string) => {
  if (typeof window.gtag !== 'undefined' && GA_MEASUREMENT_ID) {
    window.gtag('config', GA_MEASUREMENT_ID, {
      page_path: url,
    })
  }
}

// Event tracking
type GtagEvent = {
  action: string
  category: string
  label?: string
  value?: number
}

export const event = ({ action, category, label, value }: GtagEvent) => {
  if (typeof window.gtag !== 'undefined' && GA_MEASUREMENT_ID) {
    window.gtag('event', action, {
      event_category: category,
      event_label: label,
      value: value,
    })
  }
}

// Common events
export const trackEvent = {
  // Contact form
  contactFormSubmit: (projectType?: string) => {
    event({
      action: 'submit',
      category: 'Contact',
      label: projectType,
    })
  },

  contactFormError: (error: string) => {
    event({
      action: 'error',
      category: 'Contact',
      label: error,
    })
  },

  // Newsletter
  newsletterSubscribe: () => {
    event({
      action: 'subscribe',
      category: 'Newsletter',
    })
  },

  // Project interactions
  projectView: (projectName: string) => {
    event({
      action: 'view',
      category: 'Project',
      label: projectName,
    })
  },

  projectGithubClick: (projectName: string) => {
    event({
      action: 'github_click',
      category: 'Project',
      label: projectName,
    })
  },

  projectDemoClick: (projectName: string) => {
    event({
      action: 'demo_click',
      category: 'Project',
      label: projectName,
    })
  },

  // Social media
  socialClick: (platform: string) => {
    event({
      action: 'click',
      category: 'Social',
      label: platform,
    })
  },

  // Download
  resumeDownload: () => {
    event({
      action: 'download',
      category: 'Resume',
    })
  },

  // Navigation
  navClick: (section: string) => {
    event({
      action: 'click',
      category: 'Navigation',
      label: section,
    })
  },

  // Theme
  themeToggle: (theme: string) => {
    event({
      action: 'toggle',
      category: 'Theme',
      label: theme,
    })
  },

  // Search
  search: (query: string) => {
    event({
      action: 'search',
      category: 'Search',
      label: query,
    })
  },

  // Filter
  filterProjects: (category: string) => {
    event({
      action: 'filter',
      category: 'Projects',
      label: category,
    })
  },

  // Errors
  error: (errorMessage: string, errorPage: string) => {
    event({
      action: 'error',
      category: 'Error',
      label: `${errorPage}: ${errorMessage}`,
    })
  },

  // Performance
  performance: (metric: string, value: number) => {
    event({
      action: metric,
      category: 'Performance',
      value: Math.round(value),
    })
  },
}

// User properties (for segmentation)
export const setUserProperties = (properties: Record<string, any>) => {
  if (typeof window.gtag !== 'undefined' && GA_MEASUREMENT_ID) {
    window.gtag('set', 'user_properties', properties)
  }
}

// Track outbound links
export const trackOutboundLink = (url: string, label?: string) => {
  event({
    action: 'click',
    category: 'Outbound Link',
    label: label || url,
  })
}

// Track scroll depth
let maxScrollDepth = 0

export const trackScrollDepth = () => {
  const scrollDepth = Math.round(
    (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100
  )

  const milestones = [25, 50, 75, 100]
  const currentMilestone = milestones.find(
    (m) => scrollDepth >= m && maxScrollDepth < m
  )

  if (currentMilestone) {
    maxScrollDepth = currentMilestone
    event({
      action: 'scroll',
      category: 'Engagement',
      label: `${currentMilestone}%`,
      value: currentMilestone,
    })
  }
}

// Track time on page
let startTime: number

export const startTimeTracking = () => {
  startTime = Date.now()
}

export const trackTimeOnPage = (pageName: string) => {
  if (startTime) {
    const timeSpent = Math.round((Date.now() - startTime) / 1000) // in seconds
    
    if (timeSpent > 0) {
      event({
        action: 'time_on_page',
        category: 'Engagement',
        label: pageName,
        value: timeSpent,
      })
    }
  }
}

// Initialize analytics
export const initAnalytics = () => {
  startTimeTracking()

  // Track scroll depth
  if (typeof window !== 'undefined') {
    window.addEventListener('scroll', trackScrollDepth, { passive: true })
  }

  // Track time on page before leaving
  if (typeof window !== 'undefined') {
    window.addEventListener('beforeunload', () => {
      trackTimeOnPage(window.location.pathname)
    })
  }
}

// Clean up
export const cleanupAnalytics = () => {
  if (typeof window !== 'undefined') {
    window.removeEventListener('scroll', trackScrollDepth)
  }
}

