import posthog from 'posthog-js'
import { useAuthStore } from '@/stores/auth'

let initialized = false

export function usePostHog() {
  const auth = useAuthStore()

  function init() {
    if (initialized || !auth.posthogKey) return
    posthog.init(auth.posthogKey, {
      api_host: auth.posthogHost || 'https://us.i.posthog.com',
      capture_pageview: false, // We handle this via router
      capture_pageleave: true,
      capture_exceptions: true,
    })
    if (auth.user) {
      posthog.identify(auth.user.sub)
    }
    if (auth.org) {
      posthog.group('organization', auth.org)
    }
    initialized = true
  }

  function track(event: string, properties?: Record<string, unknown>) {
    if (!initialized) return
    try {
      posthog.capture(event, properties)
    } catch {
      // Silently ignore tracking errors
    }
  }

  function trackPageview(path: string) {
    if (!initialized) return
    try {
      posthog.capture('$pageview', { $current_url: path })
    } catch {
      // Silently ignore
    }
  }

  return { init, track, trackPageview }
}

export function captureException(error: unknown, properties?: Record<string, unknown>) {
  if (!initialized) return
  try {
    posthog.captureException(error instanceof Error ? error : new Error(String(error)), {
      ...properties,
    })
  } catch {
    // Silently ignore
  }
}
