import { inject, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import analytics from '@/utils/posthog/index'
import { EVENTS } from '@/constants/events'

/**
 * PostHog Analytics 组合式函数
 *
 * 使用方式：
 * const { track, identify, trackPageView } = useAnalytics()
 */
export function useAnalytics() {
  // 获取注入的实例（如果通过插件安装）
  const injectedAnalytics = inject('analytics', analytics)

  /**
   * 追踪事件
   */
  const track = (eventName, properties = {}) => {
    return injectedAnalytics.track(eventName, properties)
  }

  /**
   * 用户标识
   */
  const identify = (userId, userProperties = {}) => {
    return injectedAnalytics.identify(userId, userProperties)
  }

  /**
   * 重置用户
   */
  const reset = () => {
    return injectedAnalytics.reset()
  }

  /**
   * 追踪页面浏览
   */
  const trackPageView = (pagePath, pageTitle = '', properties = {}) => {
    return injectedAnalytics.trackPageView(pagePath, pageTitle, properties)
  }

  /**
   * 追踪页面离开
   */
  const trackPageLeave = (pagePath, duration = 0, properties = {}) => {
    return injectedAnalytics.trackPageLeave(pagePath, duration, properties)
  }

  /**
   * 设置全局属性
   */
  const setSuperProperties = (properties) => {
    return injectedAnalytics.setSuperProperties(properties)
  }

  /**
   * 设置用户属性
   */
  const setUserProperties = (properties) => {
    return injectedAnalytics.setUserProperties(properties)
  }

  /**
   * 刷新事件队列
   */
  const flush = () => {
    return injectedAnalytics.flush()
  }

  /**
   * 获取当前用户ID
   */
  const getDistinctId = () => {
    return injectedAnalytics.getDistinctId()
  }

  /**
   * 获取会话ID
   */
  const getSessionId = () => {
    return injectedAnalytics.getSessionId()
  }

  return {
    // 核心方法
    track,
    identify,
    reset,
    trackPageView,
    trackPageLeave,
    setSuperProperties,
    setUserProperties,
    flush,
    getDistinctId,
    getSessionId,

    // 事件常量
    EVENTS,

    // 原始实例（高级用途）
    analytics: injectedAnalytics,
  }
}

export default useAnalytics