<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useSearch } from '@/composables/useSearch'
import SearchResults from './SearchResults.vue'

const auth = useAuthStore()
const router = useRouter()
const { query, results, loading, open, error, close } = useSearch(() => auth.org)

function goToSearchPage() {
  const q = query.value.trim()
  close()
  router.push({ name: 'search', params: { org: auth.org }, query: q ? { q } : {} })
}

function onKeydown(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    close()
    return
  }
  if (e.key === 'Enter') {
    e.preventDefault()
    if (results.value.length > 0 && !e.shiftKey) {
      const first = results.value[0]
      const route = first.doc_type === 'spec'
        ? `/app/${auth.org}/specs/${first.repo_owner}/${first.repo_name}/${first.file_path}`
        : `/app/${auth.org}/docs/${first.repo_owner}/${first.repo_name}/${first.file_path}`
      close()
      router.push(route)
    } else {
      goToSearchPage()
    }
  }
}
</script>

<template>
  <div class="relative">
    <input
      v-model="query"
      type="search"
      placeholder="Search specs..."
      class="bg-surface-light dark:bg-[#0a0f1a] border border-border-light dark:border-slate-700 text-slate-800 dark:text-slate-200 placeholder-slate-400 dark:placeholder-slate-500 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent-500 focus:border-transparent w-64"
      @keydown="onKeydown"
    />
    <svg
      v-if="loading"
      class="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-slate-400"
      fill="none" viewBox="0 0 24 24"
    >
      <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
      <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
    </svg>
    <div v-if="open" class="absolute top-full left-0 right-0 mt-1 z-50">
      <SearchResults :results="results" :error="error" @close="close" />
      <button
        v-if="results.length > 0"
        class="w-full text-center text-xs text-accent-500 hover:text-accent-600 bg-surface-light dark:bg-surface-alt border border-t-0 border-border-light dark:border-slate-700 rounded-b-lg py-2"
        @click="goToSearchPage"
      >
        View all results
      </button>
    </div>
  </div>
</template>
