/**
 * 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 { logger } from '../utils/logger'
import PostHog, { PostHogOptions } 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) {
    logger.log('[Analytics] Already initialized')
    return posthogClient
  }

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

  try {
    const config: PostHogOptions = {
      host: POSTHOG_HOST,
      enableSessionReplay: true,
      sessionReplayConfig: {
        maskAllTextInputs: true,
        captureNetworkTelemetry: true,
      },
      flushAt: 10,
    }

    posthogClient = new PostHog(POSTHOG_API_KEY, config)

    logger.log('[Analytics] PostHog initialized with session replay')
    return posthogClient
  } catch (error) {
    logger.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__) {
    logger.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__) {
    logger.log('[Analytics] identify', userId, traits ?? '')
  }
  posthogClient?.identify(userId, traits)
}

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

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

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

/**
 * Get the current session replay status
 * Note: Session replay URL is available via PostHog dashboard
 */
export async function isSessionReplayActive(): Promise<boolean> {
  return posthogClient?.isSessionReplayActive() ?? false
}
