<script setup lang="ts">
import { AnimeCard } from '~/components/ui/anime-card'
import { search, type Result } from '~/openapi/search'

const route = useRoute()
const searchQuery = ref(route.query.title as string || '')

const results = ref<Result[]>([])
const isLoading = ref(false)
const error = ref<unknown>(null)

watchEffect(async () => {
    if (!searchQuery.value) return

    try {
        isLoading.value = true
        error.value = null
        const response = await search({ title: searchQuery.value })
        results.value = response.data.results || []
    } catch (err) {
        error.value = err
        console.error('Search failed:', err)
    } finally {
        isLoading.value = false
    }
}, {
    flush: 'post'
})
</script>

<template>
    <div class="py-4 px-32">
        <div v-if="isLoading">
            Loading results...
        </div>

        <div v-if="error">
            Error loading results: {{ error }}
        </div>

        <div v-if="results.length > 0"
            class="grid grid-cols-[repeat(auto-fill,16rem)] justify-around gap-8 grid-flow-row">
            <div v-for="item in results" :key="item.id" class="flex w-[16rem]">
                <AnimeCard :item="item" />
            </div>
        </div>

        <div v-if="!isLoading && !error && results.length === 0 && searchQuery">
            No results found for "{{ searchQuery }}"
        </div>
    </div>
</template>
