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

      <!-- 主 Tab：默认全部视频，分类/专辑收进第二页 -->
      <nav class="flex items-end gap-8 mb-10 border-b border-art-border" aria-label="视频浏览切换">
        <button
          type="button"
          class="relative pb-3 text-sm tracking-wide transition-colors"
          :class="mainTab === 'videos' ? 'text-art-text' : 'text-art-muted hover:text-art-text'"
          @click="switchMainTab('videos')"
        >
          全部视频
          <span
            v-if="mainTab === 'videos'"
            class="absolute left-0 right-0 -bottom-px h-0.5 bg-art-accent"
          />
        </button>
        <button
          type="button"
          class="relative pb-3 text-sm tracking-wide transition-colors"
          :class="mainTab === 'browse' ? 'text-art-text' : 'text-art-muted hover:text-art-text'"
          @click="switchMainTab('browse')"
        >
          分类 &amp; 专辑
          <span
            v-if="mainTab === 'browse'"
            class="absolute left-0 right-0 -bottom-px h-0.5 bg-art-accent"
          />
        </button>
      </nav>

      <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 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-art-border rounded-full text-sm text-art-text hover:border-art-accent hover:text-art-accent transition-colors"
          @click="retry"
        >
          重试
        </button>
      </div>

      <!-- Tab 面板：out-in 淡入上移，切换时不走全页 loading 以免打断动画 -->
      <Transition v-else name="videos-tab" mode="out-in">
        <div :key="mainTab" class="videos-tab-panel">
          <!-- 全部视频 -->
          <template v-if="mainTab === 'videos'">
            <div v-if="categories.length" class="mb-8">
              <label class="sr-only" for="video-cat-filter">按分类筛选</label>
              <select
                id="video-cat-filter"
                class="bg-transparent border-0 border-b border-art-border text-sm text-art-text py-1.5 pr-8 focus:outline-none focus:border-art-accent cursor-pointer"
                :value="activeCategory"
                @change="onVideoFilterChange"
              >
                <option :value="0">全部分类</option>
                <option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
              </select>
            </div>

            <div v-if="panelLoading" class="flex justify-center py-16">
              <div class="animate-spin h-8 w-8 border-t-2 border-art-accent rounded-full" />
            </div>
            <template v-else>
              <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-art-border 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-art-border flex items-center justify-center">
                        <Icon name="play" :size="20" class="text-art-text ml-0.5" />
                      </div>
                    </div>
                  </div>
                  <div class="p-4">
                    <h4 class="text-art-text 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 rounded-xl border border-dashed border-art-border">
                暂无视频
              </div>
            </template>
          </template>

          <!-- 分类 & 专辑 -->
          <template v-else>
            <div v-if="categories.length" class="mb-12">
              <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
                  class="group p-5 rounded-xl border cursor-pointer transition-colors"
                  :class="activeCategory === 0 ? 'border-art-accent/50 bg-art-accent/5' : 'border-art-border hover:border-art-accent/30 hover:bg-art-text/5'"
                  @click="selectBrowseCategory(0)"
                >
                  <h4 class="text-art-text font-medium">全部专辑</h4>
                  <p class="text-xs text-art-muted mt-2">查看所有分类下的专辑</p>
                </div>
                <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-art-border hover:border-art-accent/30 hover:bg-art-text/5'"
                  @click="selectBrowseCategory(cat.id)"
                >
                  <h4 class="text-art-text 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
              class="mb-10 text-center text-art-muted text-sm py-6 border border-dashed border-art-border rounded-xl"
            >
              暂无视频分类，请先在后台创建分类
            </div>

            <div v-if="panelLoading" class="flex justify-center py-16">
              <div class="animate-spin h-8 w-8 border-t-2 border-art-accent rounded-full" />
            </div>
            <template v-else>
              <div v-if="albums.length">
                <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-art-border 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-art-border 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-art-text/5 flex items-center justify-center">
                          <Icon name="play" :size="12" class="text-art-muted" />
                        </div>
                      </div>
                    </div>
                    <div class="p-4 cursor-pointer" @click="router.push(`/videos/albums/${album.id}`)">
                      <h4 class="text-art-text 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="text-center text-art-muted text-sm py-10 border border-dashed border-art-border rounded-xl"
              >
                暂无专辑
              </div>
            </template>
          </template>
        </div>
      </Transition>
    </div>
  </section>
</template>

<script setup lang="ts">
/**
 * 前台视频页：双主 Tab + 卡片圆角边框（对齐改前视觉）+ Tab 切换过渡。
 */
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()
/** 首屏全页 loading */
const loading = ref(false)
/** Tab 内局部 loading，避免打断 Transition */
const panelLoading = ref(false)
const error = ref('')
const categories = ref<VideoCategory[]>([])
const albums = ref<VideoAlbum[]>([])
const videos = ref<VideoItem[]>([])
const mainTab = ref<'videos' | 'browse'>('videos')
const activeCategory = ref(0)
const { initObserver } = useScrollAnimation()

/** 切换主 Tab；数据用 panelLoading，保证面板过渡可见 */
async function switchMainTab(tab: 'videos' | 'browse') {
  if (mainTab.value === tab) return
  mainTab.value = tab
  if (tab === 'videos') await loadVideos(true)
  else await loadAlbums(true)
}

function onVideoFilterChange(e: Event) {
  const val = Number((e.target as HTMLSelectElement).value) || 0
  activeCategory.value = val
  loadVideos(true)
}

function selectBrowseCategory(catId: number) {
  activeCategory.value = catId
  loadAlbums(true)
}

/** @param silent 为 true 时用面板内 loading，不盖住 Tab 过渡 */
async function loadVideos(silent = false) {
  if (silent) panelLoading.value = true
  else loading.value = true
  error.value = ''
  try {
    const catId = activeCategory.value || undefined
    videos.value = await fetchVideos(catId)
  } catch (err) {
    error.value = '加载失败，请稍后重试'
    console.error('加载视频列表失败:', err)
  } finally {
    loading.value = false
    panelLoading.value = false
    await initObserver()
  }
}

async function loadAlbums(silent = false) {
  if (silent) panelLoading.value = true
  else loading.value = true
  error.value = ''
  try {
    const catId = activeCategory.value || undefined
    albums.value = await fetchVideoAlbums(catId)
  } catch (err) {
    error.value = '加载失败，请稍后重试'
    console.error('加载专辑失败:', err)
  } finally {
    loading.value = false
    panelLoading.value = false
    await initObserver()
  }
}

async function loadAll() {
  loading.value = true
  error.value = ''
  try {
    categories.value = await fetchVideoCategories()
    videos.value = await fetchVideos()
  } catch (err) {
    error.value = '加载失败，请稍后重试'
    console.error('加载视频页失败:', err)
  } finally {
    loading.value = false
    await initObserver()
  }
}

function retry() {
  if (mainTab.value === 'videos') {
    if (!categories.value.length) loadAll()
    else loadVideos()
  } else {
    loadAlbums()
  }
}

onMounted(loadAll)
</script>

<style scoped>
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
.videos-tab-enter-active,
.videos-tab-leave-active {
  transition: opacity 0.2s ease-out, transform 0.2s ease-out;
}
.videos-tab-enter-from {
  opacity: 0;
  transform: translateY(6px);
}
.videos-tab-leave-to {
  opacity: 0;
  transform: translateY(-4px);
}
</style>
