import { ref, onMounted, onUnmounted, inject } from 'vue'
import pageTracker from '@/utils/posthog/page-tracker'
import performanceTracker from '@/utils/posthog/performance-tracker'

/**
 * 页面追踪组合式函数
 * 自动处理页面浏览、停留时长、滚动等
 *
 * 使用方式：
 * const { onScroll, onRefresh, onLoadMore } = usePageTracking({
 *   pagePath: '/pages/news/list',
 *   pageTitle: '资讯列表',
 * })
 */
export function usePageTracking(options = {}) {
  const {
    pagePath = '',
    pageTitle = '',
    pageQuery = {},
    trackPerformance = true,
  } = options

  // 页面加载状态
  const isLoaded = ref(false)
  // 当前页码
  const currentPage = ref(1)

  // 页面进入
  const onPageEnter = () => {
    // 开始性能追踪
    if (trackPerformance) {
      performanceTracker.startPageLoad(pagePath)
    }

    // 页面浏览追踪
    pageTracker.onPageEnter(pagePath, pageTitle, pageQuery)
  }

  // 页面加载完成
  const onPageReady = () => {
    isLoaded.value = true

    // 结束性能追踪
    if (trackPerformance) {
      performanceTracker.endPageLoad(pagePath)
    }
  }

  // 页面离开
  const onPageLeave = () => {
    pageTracker.onPageLeave()
  }

  // 页面滚动
  const onScroll = (scrollInfo) => {
    pageTracker.onPageScroll(scrollInfo)
  }

  // 下拉刷新
  const onRefresh = () => {
    pageTracker.onPullDownRefresh()
    currentPage.value = 1
  }

  // 加载更多
  const onLoadMore = () => {
    currentPage.value++
    pageTracker.onReachBottom(currentPage.value)
  }

  // 设置页面高度
  const setPageHeight = (height) => {
    pageTracker.setPageHeight(height)
  }

  // 获取停留时长
  const getDuration = () => {
    return pageTracker.getDuration()
  }

  return {
    // 状态
    isLoaded,
    currentPage,

    // 生命周期方法
    onPageEnter,
    onPageReady,
    onPageLeave,

    // 事件处理
    onScroll,
    onRefresh,
    onLoadMore,

    // 工具方法
    setPageHeight,
    getDuration,
  }
}

export default usePageTracking