<script setup lang="ts">
/**
 * 从视频库选择视频（供作品表单等使用）
 */
import { ref, watch, computed } from 'vue'
import { getAdminVideos, type VideoItem } from '../../services/api'
import Icon from '../Icon.vue'

const props = defineProps<{ show: boolean }>()
const emit = defineEmits<{ 'update:show': [value: boolean]; select: [video: VideoItem] }>()

const loading = ref(false)
const videos = ref<VideoItem[]>([])
const keyword = ref('')

const filtered = computed(() => {
  const kw = keyword.value.trim().toLowerCase()
  if (!kw) return videos.value
  return videos.value.filter(v => v.title.toLowerCase().includes(kw))
})

const loadVideos = async () => {
  loading.value = true
  try {
    videos.value = await getAdminVideos()
  } finally {
    loading.value = false
  }
}

watch(() => props.show, (v) => { if (v) loadVideos() })

const handleClose = () => emit('update:show', false)

const handleSelect = (video: VideoItem) => {
  emit('select', video)
  handleClose()
}
</script>

<template>
  <Teleport to="body">
    <div v-if="show" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4" @click.self="handleClose">
      <div class="admin-card max-w-3xl w-full max-h-[85vh] flex flex-col">
        <div class="flex items-center justify-between mb-4 pb-4 border-b border-white/10">
          <h2 class="text-xl font-serif italic text-white">从视频库选择</h2>
          <button type="button" class="text-white/40 hover:text-white" @click="handleClose">
            <Icon name="x" :size="20" />
          </button>
        </div>

        <input v-model="keyword" type="text" placeholder="搜索视频标题..." class="admin-input mb-4" />

        <div class="flex-1 overflow-y-auto space-y-2">
          <div v-if="loading" class="text-center py-12 text-art-muted">加载中...</div>
          <div v-else-if="filtered.length === 0" class="text-center py-12 text-art-muted">暂无视频</div>
          <button
            v-for="video in filtered"
            :key="video.id"
            type="button"
            class="w-full flex items-center gap-4 p-3 rounded-lg border border-white/10 hover:border-art-accent/50 hover:bg-white/5 text-left transition-colors"
            @click="handleSelect(video)"
          >
            <div class="w-24 h-14 rounded overflow-hidden bg-black/40 shrink-0">
              <img v-if="video.cover" :src="video.cover" class="w-full h-full object-cover" alt="" />
              <div v-else class="w-full h-full flex items-center justify-center text-art-muted">
                <Icon name="play" :size="20" />
              </div>
            </div>
            <div class="min-w-0 flex-1">
              <div class="text-white font-medium truncate">{{ video.title }}</div>
              <div class="text-xs text-art-muted">{{ video.categoryName || '未分类' }}</div>
            </div>
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>
