import { ref } from 'vue'
import searchTracker from '@/utils/posthog/search-tracker'

/**
 * 搜索追踪组合式函数
 *
 * 使用方式：
 * const {
 *   onSearchFocus,
 *   onSearch,
 *   onSearchResult,
 *   onResultClick,
 * } = useSearchTracking()
 */
export function useSearchTracking() {
  // 当前搜索关键词
  const currentQuery = ref('')
  // 搜索结果数量
  const resultCount = ref(0)

  /**
   * 搜索框聚焦
   */
  const onSearchFocus = (pagePath = '') => {
    searchTracker.onSearchFocus(pagePath)
  }

  /**
   * 执行搜索
   */
  const onSearch = (params) => {
    currentQuery.value = params.query || ''
    searchTracker.onSearch(params)
  }

  /**
   * 搜索结果返回
   */
  const onSearchResult = (result) => {
    resultCount.value = result.total || result.list?.length || 0
    searchTracker.onSearchResult(result)
  }

  /**
   * 点击搜索结果
   */
  const onResultClick = (item, position) => {
    searchTracker.onResultClick(item, position)
  }

  /**
   * 点击搜索建议
   */
  const onSuggestionClick = (suggestion, position) => {
    searchTracker.onSuggestionClick(suggestion, position)
    currentQuery.value = suggestion
  }

  /**
   * 点击热门搜索
   */
  const onHotSearchClick = (keyword, position) => {
    searchTracker.onHotSearchClick(keyword, position)
    currentQuery.value = keyword
  }

  /**
   * 点击搜索历史
   */
  const onHistoryClick = (keyword, position) => {
    searchTracker.onHistoryClick(keyword, position)
    currentQuery.value = keyword
  }

  /**
   * 清空搜索历史
   */
  const onHistoryClear = () => {
    searchTracker.onHistoryClear()
  }

  /**
   * 重置搜索状态
   */
  const reset = () => {
    currentQuery.value = ''
    resultCount.value = 0
    searchTracker.reset()
  }

  return {
    // 状态
    currentQuery,
    resultCount,

    // 方法
    onSearchFocus,
    onSearch,
    onSearchResult,
    onResultClick,
    onSuggestionClick,
    onHotSearchClick,
    onHistoryClick,
    onHistoryClear,
    reset,
  }
}

export default useSearchTracking