<script setup>
import { postApi } from '@/api/postApi'
import ArticleListItem from '@/components/ArticleListItem.vue'
import { useIntersectionObserver } from '@vueuse/core'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const searchInput = ref('')
const loadingTrigger = ref(null)
const articles = ref([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const limit = 10

const fetchArticles = async () => {
    if (loading.value) return
    loading.value = true
    try {
        const { data } = await postApi.list({
            page: currentPage.value,
            limit,
            keyword: searchInput.value
        })
        if (data.items?.length === 0) {
            hasMore.value = false
        } else {
            articles.value.push(...data.items)
            currentPage.value += 1
        }
    } catch (error) {
        console.error('Failed to fetch articles:', error)
    } finally {
        loading.value = false
    }
}

useIntersectionObserver(
    loadingTrigger,
    ([{ isIntersecting }]) => {
        if (isIntersecting && !loading.value && hasMore.value) {
            fetchArticles()
        }
    },
    {
        threshold: 0,
        rootMargin: '100px'
    }
)


const handleSearch = () => {
    articles.value = []
    currentPage.value = 1
    hasMore.value = true
    fetchArticles()
}

const handleKeyup = (e) => {
    if (e.key === 'Enter') {
        handleSearch()
    }
}

onMounted(() => {
    fetchArticles()
})
</script>

<template>
    <div class="h-full flex flex-col bg-gray-50">
        <div class="flex-none bg-white border-b border-gray-200 sticky top-0 z-40 shadow-sm">
            <div class="p-4">
                <div class="relative">
                    <input type="search" v-model="searchInput" @keyup="handleKeyup" placeholder="搜索曲谱..." class="w-full pl-10 pr-4 py-2.5 text-gray-600 bg-gray-50 border border-gray-200 rounded-full
                               focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent
                               placeholder:text-gray-400">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                        </svg>
                    </span>
                </div>
            </div>
        </div>

        <div class="flex-1 overflow-y-auto">
            <div class="container max-w-2xl mx-auto p-4">
                <div class="grid gap-6">
                    <ArticleListItem v-for="article in articles" :key="article.id" :article="article" />
                </div>

                <div ref="loadingTrigger" class="py-4 text-center" v-show="hasMore || loading">
                    <div v-if="loading"
                        class="w-8 h-8 mx-auto border-2 border-gray-200 border-t-primary-500 rounded-full animate-spin">
                    </div>
                    <div v-else class="h-8">
                        <!-- Empty space for intersection observer -->
                    </div>
                </div>

                <div v-if="!hasMore && articles.length > 0" class="text-center text-gray-500 py-4">
                    没有更多曲谱了
                </div>

                <div v-if="!hasMore && articles.length === 0" class="text-center text-gray-500 py-12">
                    暂无曲谱
                </div>
            </div>
        </div>
    </div>
</template>
