/**
 * PostHog Analytics Wrapper
 * Provides type-safe access to PostHog for product analytics and feature flags.
 * posthog-js is an optional peer dependency — only import this file if you have it installed.
 */

import type {
  AnalyticsProvider,
  AnalyticsEvent,
  PageViewEvent,
  UserIdentity,
  FeatureFlagResult,
} from '../types'

// posthog-js is optional — dynamic import to avoid hard dependency
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PostHogInstance = any

let posthog: PostHogInstance = null

async function loadPostHog(): Promise<PostHogInstance> {
  if (posthog) return posthog
  try {
    const mod = await import('posthog-js')
    posthog = mod.default
    return posthog
  } catch {
    return null
  }
}

export class PostHogProvider implements AnalyticsProvider {
  name = 'posthog'
  initialized = false
  private started = false
  private apiKey: string
  private apiHost: string
  private debug: boolean
  private options: Record<string, unknown>
  private ph: PostHogInstance = null
  private pending: Array<(ph: PostHogInstance) => void> = []

  constructor(apiKey: string, apiHost = 'https://us.i.posthog.com', debug = false, options: Record<string, unknown> = {}) {
    this.options = options
    this.apiKey = apiKey
    this.apiHost = apiHost
    this.debug = debug
  }

  initialize(): void {
    if (typeof window === 'undefined') return
    if (this.initialized) return
    if (!this.apiKey) {
      if (this.debug) {
        console.warn('[PostHog] No API key provided, skipping initialization')
      }
      return
    }

    this.started = true
    loadPostHog().then((ph) => {
      if (!ph) return

      ph.init(this.apiKey, {
        api_host: this.apiHost,
        person_profiles: 'identified_only',
        capture_pageview: false,
        capture_pageleave: true,
        autocapture: true,
        persistence: 'localStorage+cookie',
        // Session replay follows the PostHog project setting; inputs stay masked.
        session_recording: { maskAllInputs: true },
        ...this.options,
        loaded: (instance: PostHogInstance) => {
          if (this.debug) {
            console.log('[PostHog] Loaded successfully')
            instance.debug()
          }
        },
      })

      this.ph = ph
      this.initialized = true
      for (const run of this.pending.splice(0)) run(ph)

      if (this.debug) {
        console.log('[PostHog] Initialized with host:', this.apiHost)
      }
    })
  }

  identify(identity: UserIdentity): void {
    if (!this.isReady()) return this.defer(() => this.identify(identity))

    const userProperties: Record<string, unknown> = {}
    if (identity.email) userProperties.email = identity.email
    if (identity.name) userProperties.name = identity.name
    if (identity.properties) Object.assign(userProperties, identity.properties)

    this.ph.identify(identity.userId, userProperties)

    if (this.debug) {
      console.log('[PostHog] User identified:', identity.userId)
    }
  }

  reset(): void {
    if (!this.isReady()) return this.defer(() => this.reset())
    this.ph.reset()
    if (this.debug) console.log('[PostHog] User reset')
  }

  trackEvent(event: AnalyticsEvent): void {
    if (!this.isReady()) return this.defer(() => this.trackEvent(event))

    this.ph.capture(event.name, {
      category: event.category,
      timestamp: event.timestamp || Date.now(),
      ...event.properties,
    })

    if (this.debug) {
      console.log('[PostHog] Event tracked:', event.name, event.properties)
    }
  }

  trackPageView(pageView: PageViewEvent): void {
    if (!this.isReady()) return this.defer(() => this.trackPageView(pageView))

    this.ph.capture('$pageview', {
      $current_url: pageView.path,
      $title: pageView.title,
      $referrer: pageView.referrer,
      ...pageView.properties,
    })

    if (this.debug) {
      console.log('[PostHog] Page view tracked:', pageView.path)
    }
  }

  setUserProperties(properties: Record<string, unknown>): void {
    if (!this.isReady()) return
    this.ph.setPersonProperties(properties)
    if (this.debug) console.log('[PostHog] User properties set:', properties)
  }

  getFeatureFlag(
    key: string,
    defaultValue: boolean | string | number = false
  ): FeatureFlagResult {
    if (!this.isReady()) {
      return { key, value: defaultValue, source: 'default' }
    }

    const value = this.ph.getFeatureFlag(key)

    if (value === undefined || value === null) {
      return { key, value: defaultValue, source: 'default' }
    }

    if (this.debug) console.log('[PostHog] Feature flag:', key, '=', value)

    return {
      key,
      value: value as boolean | string | number,
      source: 'posthog',
    }
  }

  isFeatureEnabled(key: string): boolean {
    if (!this.isReady()) return false
    return this.ph.isFeatureEnabled(key) ?? false
  }

  reloadFeatureFlags(): void {
    if (!this.isReady()) return
    this.ph.reloadFeatureFlags()
  }

  onFeatureFlags(callback: (flags: string[]) => void): void {
    if (!this.isReady()) return
    this.ph.onFeatureFlags(callback)
  }

  group(groupType: string, groupKey: string, properties?: Record<string, unknown>): void {
    if (!this.isReady()) return
    this.ph.group(groupType, groupKey, properties)
    if (this.debug) console.log('[PostHog] Group set:', groupType, groupKey)
  }

  /** Hold an event, page view, identify or reset until posthog-js has loaded, if it is going to (a key, a browser, init started). */
  private defer(run: () => void): void {
    if (typeof window === 'undefined' || !this.apiKey || !this.started) return
    if (this.pending.length < 100) this.pending.push(run as (ph: PostHogInstance) => void)
  }

  /** Run once PostHog is loaded (now, or right after init). */
  private whenReady(run: (ph: PostHogInstance) => void): void {
    if (typeof window === 'undefined') return
    if (this.isReady()) run(this.ph)
    else this.pending.push(run)
  }

  /** Super properties sent with every later event. `once` keeps the first value (first-touch). */
  register(properties: Record<string, unknown>, once = false): void {
    this.whenReady((ph) => (once ? ph.register_once(properties) : ph.register(properties)))
  }

  /** Person properties set only if not already set (initial_* style). Applies once the person is identified. */
  setPersonPropertiesOnce(properties: Record<string, unknown>): void {
    this.whenReady((ph) => ph.setPersonProperties({}, properties))
  }

  startSessionRecording(): void {
    if (!this.isReady()) return
    this.ph.startSessionRecording()
  }

  stopSessionRecording(): void {
    if (!this.isReady()) return
    this.ph.stopSessionRecording()
  }

  getSessionId(): string | undefined {
    if (!this.isReady()) return undefined
    return this.ph.get_session_id()
  }

  /** Before posthog-js has loaded the choice is held and applied right after init, ahead of the events queued behind it. */
  optIn(): void {
    this.whenReady((ph) => ph.opt_in_capturing())
  }

  optOut(): void {
    this.whenReady((ph) => ph.opt_out_capturing())
  }

  hasOptedOut(): boolean {
    if (!this.isReady()) return false
    return this.ph.has_opted_out_capturing()
  }

  getInstance(): PostHogInstance {
    return this.isReady() ? this.ph : null
  }

  private isReady(): boolean {
    if (typeof window === 'undefined') return false
    return this.initialized && !!this.apiKey && !!this.ph
  }
}
