<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import type { SpecSearchResult } from '@/api/types'
import StatusBadge from '@/components/common/StatusBadge.vue'

defineProps<{ results: SpecSearchResult[]; error?: string | null }>()
const emit = defineEmits<{ close: [] }>()
const auth = useAuthStore()
const router = useRouter()

function navigate(result: SpecSearchResult) {
  const route = result.doc_type === 'spec'
    ? `/app/${auth.org}/specs/${result.repo_owner}/${result.repo_name}/${result.file_path}`
    : `/app/${auth.org}/docs/${result.repo_owner}/${result.repo_name}/${result.file_path}`
  emit('close')
  router.push(route)
}
</script>

<template>
  <div class="bg-surface-light dark:bg-surface-alt border border-border-light dark:border-slate-700 rounded-lg shadow-lg max-h-96 overflow-y-auto min-w-80">
    <div v-if="error" class="px-4 py-3 text-sm text-red-500">
      {{ error }}
    </div>
    <div v-else-if="results.length === 0" class="px-4 py-3 text-sm text-slate-500">
      No results found.
    </div>
    <button
      v-for="r in results"
      :key="`${r.repo_full_name}/${r.file_path}`"
      class="w-full text-left px-4 py-3 hover:bg-surface-light-alt dark:hover:bg-surface-elevated border-b border-border-light/60 dark:border-slate-800 last:border-0"
      @click="navigate(r)"
    >
      <div class="flex items-center gap-2 mb-1">
        <span class="font-medium text-sm text-slate-800 dark:text-slate-200">{{ r.title }}</span>
        <span v-if="r.doc_type !== 'spec'" class="text-xs px-1.5 py-0.5 rounded bg-surface-light-elevated dark:bg-slate-700 text-slate-500">{{ r.doc_type }}</span>
        <StatusBadge :status="r.status" />
      </div>
      <div class="text-xs text-slate-500">{{ r.repo_full_name }}</div>
      <div v-if="r.heading" class="text-xs text-slate-400 mt-0.5">{{ r.heading }}</div>
      <p v-if="r.snippet" class="text-xs text-slate-500 mt-1 line-clamp-2">{{ r.snippet }}</p>
    </button>
  </div>
</template>
