<script setup lang="ts">
/**
 * 视频库：分类 tabs（暗色走 AppPageShell themeVars）+ 专辑封面横滑 + 视频列表。
 */
import { ref, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import ContentPageHeader from '../../components/ContentPageHeader.vue'
import {
  getVideos,
  getVideoCategories,
  getVideoAlbums,
  type VideoItem,
  type VideoAlbum,
} from '@/api'
import { resolveMediaUrl } from '@/utils/request'

interface VideoCategory {
  id: number
  name: string
}

const loading = ref(false)
const categories = ref<VideoCategory[]>([])
const albums = ref<VideoAlbum[]>([])
const list = ref<VideoItem[]>([])
const activeTab = ref('all')

const tabs = ref<{ name: string, title: string }[]>([{ name: 'all', title: '全部' }])

async function loadCategories() {
  try {
    const cats = await getVideoCategories()
    categories.value = (cats || []) as VideoCategory[]
    tabs.value = [
      { name: 'all', title: '全部' },
      ...categories.value.map(c => ({ name: String(c.id), title: c.name })),
    ]
  }
  catch {
    categories.value = []
    tabs.value = [{ name: 'all', title: '全部' }]
  }
}

/** 专辑随分类过滤（全部时不过滤） */
async function loadAlbums() {
  try {
    const params: Record<string, unknown> = {}
    if (activeTab.value !== 'all') params.categoryId = Number(activeTab.value)
    albums.value = await getVideoAlbums(params) || []
  }
  catch {
    albums.value = []
  }
}

async function loadVideos() {
  loading.value = true
  try {
    const params: Record<string, unknown> = {}
    if (activeTab.value !== 'all') params.categoryId = Number(activeTab.value)
    list.value = await getVideos(params) || []
  }
  catch (e: unknown) {
    uni.showToast({ title: e instanceof Error ? e.message : '加载失败', icon: 'none' })
  }
  finally {
    loading.value = false
  }
}

async function refresh() {
  await loadCategories()
  await Promise.all([loadAlbums(), loadVideos()])
}

onShow(refresh)

watch(activeTab, async () => {
  await Promise.all([loadAlbums(), loadVideos()])
})

const openVideo = (id: string) => uni.navigateTo({ url: `/subPackages/content/pages/videos/detail?id=${id}` })
const openAlbum = (id: number) => uni.navigateTo({ url: `/subPackages/content/pages/videos/album?id=${id}` })

const metaLine = (item: VideoItem) => {
  const bits = [item.categoryName, item.createdAt].filter(Boolean)
  return bits.join(' · ')
}
</script>

<template>
  <AppPageShell>
    <AppNavbar title="视频" show-back />
    <view class="page-pad">
      <ContentPageHeader
        eyebrow="Videos"
        title="视频库"
        desc="专辑与最新成片，按分类浏览。"
      />

      <wd-tabs v-if="tabs.length > 1" v-model="activeTab" slidable="always">
        <wd-tab v-for="tab in tabs" :key="tab.name" :name="tab.name" :title="tab.title" />
      </wd-tabs>

      <view v-if="albums.length" class="albums animate-reveal">
        <text class="font-mono-label text-art-muted">专辑</text>
        <scroll-view scroll-x class="album-scroll" :show-scrollbar="false">
          <view class="album-row">
            <view
              v-for="alb in albums"
              :key="alb.id"
              class="album-card art-card art-card-press"
              @click="openAlbum(alb.id)"
            >
              <image
                v-if="alb.cover"
                class="album-cover"
                :src="resolveMediaUrl(String(alb.cover))"
                mode="aspectFill"
              />
              <view v-else class="album-cover album-cover--empty" />
              <view class="album-meta">
                <text class="album-name">{{ alb.name }}</text>
                <text v-if="alb.videoCount != null" class="album-count text-art-muted">
                  {{ alb.videoCount }} 集
                </text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="list-label font-mono-label text-art-muted">最新视频</view>
      <view
        v-for="item in list"
        :key="item.id"
        class="art-card art-card-press card"
        @click="openVideo(item.id)"
      >
        <view class="cover-wrap">
          <image
            v-if="item.cover"
            class="cover"
            :src="resolveMediaUrl(String(item.cover))"
            mode="aspectFill"
          />
          <view v-else class="cover cover--empty" />
          <view class="play-badge">
            <wd-icon name="play-circle" size="36px" color="#fff" />
          </view>
        </view>
        <view class="body">
          <text class="title">{{ item.title }}</text>
          <text v-if="metaLine(item)" class="meta text-art-muted">{{ metaLine(item) }}</text>
          <text v-if="item.description" class="desc text-art-muted">{{ item.description }}</text>
        </view>
      </view>

      <wd-loading v-if="loading" />
      <wd-empty v-if="!loading && !list.length" description="暂无视频" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 80rpx; }
.albums { margin: 28rpx 0 36rpx; }
.album-scroll { margin-top: 16rpx; white-space: nowrap; }
.album-row { display: inline-flex; gap: 20rpx; padding-bottom: 8rpx; }
.album-card {
  width: 280rpx;
  overflow: hidden;
  flex-shrink: 0;
}
.album-cover {
  width: 280rpx;
  height: 160rpx;
  display: block;
}
.album-cover--empty { background: rgba(212, 179, 131, 0.12); }
.album-meta { padding: 16rpx 20rpx 20rpx; display: flex; flex-direction: column; gap: 6rpx; }
.album-name {
  font-size: 26rpx;
  color: rgb(var(--art-text));
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.album-count { font-size: 22rpx; }
.list-label { display: block; margin-bottom: 16rpx; }
.card { margin-bottom: 24rpx; overflow: hidden; }
.cover-wrap { position: relative; }
.cover { width: 100%; height: 320rpx; display: block; }
.cover--empty { background: rgba(212, 179, 131, 0.1); height: 320rpx; }
.play-badge {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.22);
}
.body { padding: 24rpx 28rpx; display: flex; flex-direction: column; gap: 8rpx; }
.title { font-size: 32rpx; color: rgb(var(--art-text)); }
.meta { font-size: 22rpx; }
.desc {
  font-size: 24rpx;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
