<template>
  <section id="videos" class="page-section block animate-slide-down">
    <div class="max-w-6xl mx-auto pb-12 md:pb-20">
      <div class="mb-12">
        <h2 class="font-serif text-5xl italic text-white mb-4">视频</h2>
        <p class="text-art-muted">精选视频内容与系列专辑。</p>
      </div>

      <!-- 分类 Tab 快捷筛选 -->
      <div class="flex flex-wrap gap-2 mb-8">
        <button
          type="button"
          class="px-4 py-1.5 rounded-full text-sm border transition-colors"
          :class="activeCategory === 0 ? 'border-art-accent text-art-accent bg-art-accent/10' : 'border-white/10 text-art-muted hover:text-white'"
          @click="selectCategory(0)"
        >全部</button>
        <button
          v-for="cat in categories"
          :key="cat.id"
          type="button"
          class="px-4 py-1.5 rounded-full text-sm border transition-colors"
          :class="activeCategory === cat.id ? 'border-art-accent text-art-accent bg-art-accent/10' : 'border-white/10 text-art-muted hover:text-white'"
          @click="selectCategory(cat.id)"
        >{{ cat.name }}</button>
      </div>

      <!-- 分类概览卡片 -->
      <div v-if="categories.length" class="mb-14">
        <h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">分类</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          <div
            v-for="cat in categories"
            :key="'card-' + cat.id"
            class="group p-5 rounded-xl border cursor-pointer transition-colors"
            :class="activeCategory === cat.id ? 'border-art-accent/50 bg-art-accent/5' : 'border-white/10 hover:border-art-accent/30 hover:bg-white/5'"
            @click="selectCategory(cat.id)"
          >
            <h4 class="text-white font-medium group-hover:text-art-accent transition-colors">{{ cat.name }}</h4>
            <p v-if="cat.description" class="text-xs text-art-muted mt-2 line-clamp-2">{{ cat.description }}</p>
            <div class="flex gap-4 mt-3 text-xs text-art-muted">
              <span>{{ cat.videoCount ?? 0 }} 个视频</span>
              <span>{{ cat.albumCount ?? 0 }} 个专辑</span>
            </div>
          </div>
        </div>
      </div>
      <div v-else-if="!loading && !error" class="mb-10 text-center text-art-muted text-sm py-6 border border-dashed border-white/10 rounded-xl">
        暂无视频分类，请先在后台创建分类
      </div>

      <div v-if="loading" class="flex justify-center py-20"><div class="animate-spin h-10 w-10 border-t-2 border-art-accent rounded-full"></div></div>

      <div v-else-if="error" class="text-center py-12">
        <p class="text-red-400 mb-4">{{ error }}</p>
        <button
          type="button"
          class="px-4 py-2 border border-white/20 rounded-full text-sm text-white hover:border-art-accent hover:text-art-accent transition-colors"
          @click="loadAll"
        >重试</button>
      </div>

      <template v-else>
        <!-- 专辑 -->
        <div v-if="albums.length" class="mb-16">
          <h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">专辑</h3>
          <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            <div
              v-for="album in albums"
              :key="album.id"
              class="group rounded-xl overflow-hidden border border-white/10 hover:border-art-accent/40 transition-colors"
            >
              <div
                class="aspect-video bg-gray-900 overflow-hidden cursor-pointer"
                @click="router.push(`/videos/albums/${album.id}`)"
              >
                <img v-if="album.cover" :src="album.cover" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" alt="" />
              </div>
              <!-- 专辑预览视频缩略图 -->
              <div
                v-if="album.previewVideos?.length"
                class="flex gap-1 px-2 py-2 bg-black/30 border-t border-white/5 overflow-x-auto"
              >
                <div
                  v-for="pv in album.previewVideos"
                  :key="pv.id"
                  class="shrink-0 w-16 h-10 rounded overflow-hidden cursor-pointer border border-transparent hover:border-art-accent/50"
                  @click.stop="router.push(`/videos/${pv.id}`)"
                >
                  <img v-if="pv.cover" :src="pv.cover" class="w-full h-full object-cover" alt="" />
                  <div v-else class="w-full h-full bg-white/5 flex items-center justify-center">
                    <Icon name="play" :size="12" class="text-white/50" />
                  </div>
                </div>
              </div>
              <div class="p-4 cursor-pointer" @click="router.push(`/videos/albums/${album.id}`)">
                <h4 class="text-white font-medium group-hover:text-art-accent transition-colors">{{ album.name }}</h4>
                <p class="text-xs text-art-muted mt-1">
                  {{ album.videoCount ?? 0 }} 个视频
                  <span v-if="album.latestVideoUpdatedAt" class="ml-2">· 更新于 {{ album.latestVideoUpdatedAt }}</span>
                </p>
                <p v-if="album.categoryName" class="text-xs text-art-muted/70 mt-1">{{ album.categoryName }}</p>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="mb-10 text-center text-art-muted text-sm py-8 border border-dashed border-white/10 rounded-xl">
          暂无专辑
        </div>

        <!-- 最新视频 -->
        <div>
          <h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">最新视频</h3>
          <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            <div
              v-for="video in videos"
              :key="video.id"
              class="group cursor-pointer rounded-xl overflow-hidden border border-white/10 hover:border-art-accent/40 transition-colors"
              @click="router.push(`/videos/${video.id}`)"
            >
              <div class="aspect-video bg-black/40 relative overflow-hidden">
                <img v-if="video.cover" :src="video.cover" class="w-full h-full object-cover" alt="" />
                <div class="absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/10 transition-colors">
                  <div class="w-12 h-12 rounded-full border border-white/30 flex items-center justify-center">
                    <Icon name="play" :size="20" class="text-white ml-0.5" />
                  </div>
                </div>
              </div>
              <div class="p-4">
                <h4 class="text-white font-medium line-clamp-2">{{ video.title }}</h4>
                <p class="text-xs text-art-muted mt-1">
                  {{ video.categoryName || '未分类' }}
                  <span v-if="video.createdAt" class="ml-2">· 发布于 {{ video.createdAt }}</span>
                </p>
              </div>
            </div>
          </div>
          <div v-if="videos.length === 0" class="text-center py-12 text-art-muted">暂无视频</div>
        </div>
      </template>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { fetchVideoCategories, fetchVideoAlbums, fetchVideos, type VideoCategory, type VideoAlbum, type VideoItem } from '../services/api'
import { useScrollAnimation } from '../composables/useScrollAnimation'
import Icon from '../components/Icon.vue'

const router = useRouter()
const loading = ref(false)
const error = ref('')
const categories = ref<VideoCategory[]>([])
const albums = ref<VideoAlbum[]>([])
const videos = ref<VideoItem[]>([])
const activeCategory = ref(0)

const { initObserver } = useScrollAnimation()

/** 切换分类并重新加载数据 */
const selectCategory = (catId: number) => {
  activeCategory.value = catId
  loadData()
}

/** 加载专辑与视频列表 */
const loadData = async () => {
  loading.value = true
  error.value = ''
  try {
    const catId = activeCategory.value || undefined
    albums.value = await fetchVideoAlbums(catId)
    videos.value = await fetchVideos(catId)
  } catch (err) {
    error.value = '加载失败，请稍后重试'
    console.error('加载视频列表失败:', err)
  } finally {
    loading.value = false
    await initObserver()
  }
}

/** 加载分类并刷新列表 */
const loadAll = async () => {
  try {
    categories.value = await fetchVideoCategories()
  } catch (err) {
    error.value = '加载分类失败，请稍后重试'
    console.error('加载视频分类失败:', err)
    return
  }
  await loadData()
}

onMounted(loadAll)
</script>
