/**
 * Application monitoring and error tracking
 */

let sentryInitialized = false

/**
 * Initialize Sentry for error tracking
 */
export function initMonitoring() {
  if (typeof window === 'undefined') {
    return
  }

  const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN
  if (!dsn || sentryInitialized) {
    return
  }

  // Initialize Sentry in production
  if (process.env.NODE_ENV === 'production') {
    // Sentry will be initialized via sentry.client.config.ts
    sentryInitialized = true
  }
}

/**
 * Log error to monitoring service
 */
export function logError(error: Error, context?: Record<string, unknown>) {
  if (typeof window === 'undefined') {
    console.error('Error:', error, context)
    return
  }

  // In production, this will send to Sentry
  if (process.env.NODE_ENV === 'production' && typeof window !== 'undefined') {
    // @ts-expect-error - Sentry will be available
    if (window.Sentry) {
      // @ts-expect-error
      window.Sentry.captureException(error, { extra: context })
    }
  } else {
    console.error('Error:', error, context)
  }
}

/**
 * Log performance metric
 */
export function logPerformance(name: string, duration: number, metadata?: Record<string, unknown>) {
  if (typeof window === 'undefined') {
    return
  }

  // Log to console in development
  if (process.env.NODE_ENV === 'development') {
    console.log(`Performance: ${name} took ${duration}ms`, metadata)
  }

  // In production, send to monitoring service
  if (process.env.NODE_ENV === 'production') {
    // @ts-expect-error - Sentry will be available
    if (window.Sentry) {
      // @ts-expect-error
      window.Sentry.metrics.distribution(name, duration, { tags: metadata })
    }
  }
}

/**
 * Track custom event
 */
export function trackEvent(name: string, properties?: Record<string, unknown>) {
  if (typeof window === 'undefined') {
    return
  }

  // In production, send to analytics
  if (process.env.NODE_ENV === 'production') {
    // Add analytics tracking here
    console.log('Event:', name, properties)
  } else {
    console.log('Event:', name, properties)
  }
}

