import { ref, watch, onUnmounted } from 'vue'
import { fetchSearch } from '@/api/search'
import type { SpecSearchResult } from '@/api/types'

export function useSearch(org: () => string) {
  const query = ref('')
  const results = ref<SpecSearchResult[]>([])
  const loading = ref(false)
  const open = ref(false)
  const error = ref<string | null>(null)
  let debounceTimer: ReturnType<typeof setTimeout> | null = null

  watch(query, (val) => {
    if (debounceTimer) clearTimeout(debounceTimer)
    if (!val.trim()) {
      results.value = []
      error.value = null
      open.value = false
      return
    }
    debounceTimer = setTimeout(async () => {
      loading.value = true
      error.value = null
      try {
        const res = await fetchSearch(org(), { q: val, limit: 10 })
        results.value = res.results
        open.value = true
      } catch {
        results.value = []
        error.value = 'Search failed'
      } finally {
        loading.value = false
      }
    }, 300)
  })

  onUnmounted(() => {
    if (debounceTimer) clearTimeout(debounceTimer)
  })

  function close() {
    open.value = false
    query.value = ''
    results.value = []
    error.value = null
  }

  return { query, results, loading, open, error, close }
}
