/**
 * TabataFit PostHog Analytics Service
 * Initialize and configure PostHog for user analytics and session replay
 *
 * Follows the same pattern as purchases.ts:
 * - initializeAnalytics() called once at app startup
 * - track() helper for type-safe event tracking
 * - identifyUser() for user identification
 * - Session replay enabled for onboarding funnel analysis
 */

import PostHog, { PostHogConfig } from 'posthog-react-native'

type EventProperties = Record<string, string | number | boolean | string[]>

// PostHog configuration
const POSTHOG_API_KEY = 'phc_9MuXpbtF6LfPycCAzI4xEPhggwwZyGiy9htW0jJ0LTi'
const POSTHOG_HOST = 'https://eu.i.posthog.com'

// Singleton client instance
let posthogClient: PostHog | null = null

/**
 * Initialize PostHog SDK with session replay
 * Call this once at app startup (after store hydration)
 */
export async function initializeAnalytics(): Promise<PostHog | null> {
  if (posthogClient) {
    console.log('[Analytics] Already initialized')
    return posthogClient
  }

  // Skip initialization if no real API key is configured
  if (POSTHOG_API_KEY.startsWith('__')) {
    if (__DEV__) {
      console.log('[Analytics] No API key configured — events will be logged to console only')
    }
    return null
  }

  try {
    const config: PostHogConfig = {
      host: POSTHOG_HOST,
      // Session Replay - enabled for onboarding funnel analysis
      enableSessionReplay: true,
      sessionReplayConfig: {
        // Mask sensitive inputs (passwords, etc.)
        maskAllTextInputs: true,
        // Capture screenshots for better replay quality
        screenshotMode: 'lazy', // Only capture when needed
        // Network capture for API debugging in replays
        captureNetworkTelemetry: true,
      },
      // Autocapture configuration
      autocapture: {
        captureScreens: true,
        captureTouches: true,
      },
      // Flush events more frequently during onboarding
      flushAt: 10,
    }

    posthogClient = new PostHog(POSTHOG_API_KEY, config)

    console.log('[Analytics] PostHog initialized with session replay')
    return posthogClient
  } catch (error) {
    console.error('[Analytics] Failed to initialize PostHog:', error)
    return null
  }
}

/**
 * Get the PostHog client instance (for PostHogProvider)
 */
export function getPostHogClient(): PostHog | null {
  return posthogClient
}

/**
 * Track an analytics event
 * Safe to call even if PostHog is not initialized — logs to console in dev
 */
export function track(event: string, properties?: EventProperties): void {
  if (__DEV__) {
    console.log(`[Analytics] ${event}`, properties ?? '')
  }
  posthogClient?.capture(event, properties)
}

/**
 * Track a screen view
 */
export function trackScreen(screenName: string, properties?: EventProperties): void {
  track('$screen', { $screen_name: screenName, ...properties })
}

/**
 * Identify a user with traits
 * Call after onboarding completion to link session replays to user
 */
export function identifyUser(
  userId: string,
  traits?: EventProperties,
): void {
  if (__DEV__) {
    console.log('[Analytics] identify', userId, traits ?? '')
  }
  posthogClient?.identify(userId, traits)
}

/**
 * Set user properties (without identifying)
 */
export function setUserProperties(properties: EventProperties): void {
  if (__DEV__) {
    console.log('[Analytics] set user properties', properties)
  }
  posthogClient?.personProperties(properties)
}

/**
 * Start a new session replay recording
 * Useful for key moments like onboarding start
 */
export function startSessionRecording(): void {
  if (__DEV__) {
    console.log('[Analytics] start session recording')
  }
  posthogClient?.startSessionRecording()
}

/**
 * Stop session replay recording
 */
export function stopSessionRecording(): void {
  if (__DEV__) {
    console.log('[Analytics] stop session recording')
  }
  posthogClient?.stopSessionRecording()
}

/**
 * Get the current session URL for debugging
 */
export function getSessionReplayUrl(): string | null {
  return posthogClient?.getSessionReplayUrl() ?? null
}
