<script setup lang="ts">
const router = useRouter()

const getRandomNovel = async () => {
  try {
    const allNovels = await queryCollection('content').all() as any[]
    console.log(`Total novels found: ${allNovels.length}`)
    const novels = allNovels.filter(item => (item._path || item.id || '').includes('/novels/') && (item._path || item.id || '').endsWith('/index.md'))
    console.log(`Found ${novels.length} novels for random selection`)
    if (novels.length > 0) {
      const randomNovel = novels[Math.floor(Math.random() * novels.length)]
      const slug = (randomNovel._path || randomNovel.id || '').split('/')[2]
      if (slug) {
        console.log('Redirecting to random novel:', slug)
        await router.push(`/novels/${slug}`)
      }
    }
  } catch (error) {
    console.error('Error getting random novel:', error)
  }
}

onMounted(async () => {
  console.log('Getting random novel...')
  await getRandomNovel()
})

useSeoMeta({
  title: 'Random Novel - LastWebNovel',
  description: 'Get a random novel recommendation'
})
</script>

<template>
  <UDashboardPanel>
    <template #header>
      <UDashboardNavbar title="Random Novel" :ui="{ right: 'gap-3' }">
        <template #leading>
          <UDashboardSidebarCollapse />
        </template>
      </UDashboardNavbar>
    </template>

    <template #body>
      <UContainer class="py-8">
        <div class="text-center py-12">
          <UIcon name="i-lucide-dice-1" class="size-12 mx-auto mb-4 text-gray-400 animate-spin" />
          <h3 class="text-lg font-semibold mb-2">
            Finding a random novel...
          </h3>
          <p class="text-gray-600 dark:text-gray-400">
            Redirecting you to a random novel...
          </p>
        </div>
      </UContainer>
    </template>
  </UDashboardPanel>
</template>
