<template>
  <div class="works-page">
    <SidebarNav active="works" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部栏 -->
      <TopHeader ref="topHeaderRef" @avatar-click="showUserMenu = !showUserMenu" />

      <!-- 内容区域 -->
      <div ref="contentAreaRef" class="content-area" @scroll="handleScroll">
        <div class="toolbar">
          <div class="works-tab-bar">
            <button
              class="works-tab-item"
              :class="{ active: activeTab === 'all' }"
              @click="activeTab = 'all'"
            >
              {{ t('works.all') }}
            </button>
            <button
              class="works-tab-item"
              :class="{ active: activeTab === 'video' }"
              @click="activeTab = 'video'"
            >
              {{ t('works.video') }}
            </button>
            <button
              class="works-tab-item"
              :class="{ active: activeTab === 'image' }"
              @click="activeTab = 'image'"
            >
              {{ t('works.image') }}
            </button>
          </div>
        </div>

        <div class="filters-bar">
          <div class="filters-left">
            <div class="filter-chip">
              <a-select v-model:value="dateFilter" :placeholder="t('works.dateFilter')" size="small" :bordered="false" :popupMatchSelectWidth="false" :dropdownStyle="{ minWidth: '120px' }">
                <a-select-option value="today">{{ t('works.today') }}</a-select-option>
                <a-select-option value="week">{{ t('works.thisWeek') }}</a-select-option>
                <a-select-option value="month">{{ t('works.thisMonth') }}</a-select-option>
              </a-select>
            </div>
            <div class="filter-chip">
              <a-select v-model:value="category" :placeholder="t('works.taskType')" size="small" :bordered="false" :popupMatchSelectWidth="false" :dropdownStyle="{ minWidth: '140px' }" @change="onFilterChange">
                <a-select-option value="all">{{ t('works.all') }}</a-select-option>
                <a-select-option value="text2video">{{ t('works.textToVideo') }}</a-select-option>
                <a-select-option value="image2video">{{ t('works.imageToVideo') }}</a-select-option>
                <a-select-option value="storyboard">{{ t('works.storyboardVideo') }}</a-select-option>
              </a-select>
            </div>
            <div class="filter-chip">
              <a-select v-model:value="resolution" :placeholder="t('works.resolution')" clearable size="small" :bordered="false" :popupMatchSelectWidth="false" :dropdownStyle="{ minWidth: '100px' }">
                <a-select-option value="sd">{{ t('works.sd') }}</a-select-option>
                <a-select-option value="hd">{{ t('works.hd') }}</a-select-option>
              </a-select>
            </div>
            <div class="filter-chip">
              <a-select v-model:value="sortBy" :placeholder="t('works.ratio')" clearable size="small" :bordered="false" :popupMatchSelectWidth="false" :dropdownStyle="{ minWidth: '100px' }">
                <a-select-option label="9:16" value="9:16" />
                <a-select-option label="16:9" value="16:9" />
              </a-select>
            </div>
            <button class="filter-reset-btn" @click="resetFilters">
              <CloseOutlined style="font-size: 10px;" />
              {{ t('common.reset') }}
            </button>
          </div>
          <div class="filters-right">
            <div class="search-box">
              <SearchOutlined class="search-box-icon" @click="doSearch" />
              <a-input
                v-model="keyword"
                :placeholder="t('works.searchPlaceholder')"
                size="small"
                clearable
                @keyup.enter.native="doSearch"
              />
            </div>
          </div>
        </div>

        <div class="select-row">
          <a-checkbox :model-value="isAllSelected" @change="toggleSelectAll" size="small">{{ t('works.selectAll') }}</a-checkbox>
          <template v-if="multiSelect && selectedIds.size">
            <a-tag type="success" size="small">{{ t('works.selectedCount', { count: selectedIds.size }) }}</a-tag>
            <a-button size="small" type="primary" @click="bulkDownload" plain>{{ t('video.download') }}</a-button>
            <a-button size="small" type="danger" @click="bulkDelete" plain>{{ t('common.delete') }}</a-button>
          </template>
        </div>

    <div class="works-grid">
      <div
        v-for="item in filteredItems"
        :key="item.id"
        :ref="el => setItemRef(el, item.id)"
        :data-vid="item.id"
        class="works-grid-item"
      >
        <!-- 虚拟滚动：只渲染可视区域 + 75% 缓冲区的卡片 -->
        <template v-if="isItemVisible(item.id)">
          <a-card class="work-card" :class="{ selected: selectedIds.has(item.id) }" shadow="hover">
            <div class="thumb" @click="multiSelect ? toggleSelect(item.id) : openDetail(item)">
              <!-- 缩略图：统一使用 <img> 加载 -->
              <img
                v-if="item.thumbnailCover"
                :src="item.thumbnailCover"
                :alt="item.title"
                class="work-thumbnail-img"
                loading="lazy"
                @error="onImageError"
              />
              <div v-else class="work-placeholder" :class="{ 'is-processing': item.status === 'PROCESSING' || item.status === 'PENDING' }">
                <PlayCircleOutlined />
                <div class="placeholder-text">{{ item.status === 'PROCESSING' ? t('works.processing') : (item.status === 'PENDING' ? t('works.queuing') : t('works.noPreview')) }}</div>
              </div>
              <!-- 生成中/排队中状态的覆盖层 -->
              <div v-if="item.status === 'PROCESSING' || item.status === 'PENDING'" class="processing-overlay">
                <div class="processing-content">
                  <PlayCircleOutlined class="processing-icon" />
                  <div class="processing-text">{{ item.status === 'PROCESSING' ? t('works.processing') : t('works.queuing') }}</div>
                  <div class="progress-bar-container">
                    <div class="progress-bar-animated"></div>
                  </div>
                </div>
              </div>
              <div class="checker" v-if="multiSelect">
                <a-checkbox :model-value="selectedIds.has(item.id)" @change="() => toggleSelect(item.id)" />
              </div>
              <!-- 悬停按钮 -->
              <div class="hover-buttons-container">
                <div class="hover-create-btn left" @click.stop="createSimilar(item)">
                  <a-button type="primary" size="small" round>
                    <PlayCircleOutlined />
                    {{ t('profile.createSimilar') }}
                  </a-button>
                </div>
                <div v-if="item.category === '分镜图' || item.workType === 'STORYBOARD_IMAGE'" class="hover-create-btn right" @click.stop="goToGenerateVideo(item)">
                  <a-button type="success" size="small" round>
                    <VideoCameraOutlined />
                    {{ t('video.storyboard.generateVideo') }}
                  </a-button>
                </div>
              </div>
            </div>
            <div class="meta">
              <div class="title" :title="item.title">{{ item.title }}</div>
              <div class="sub">
                {{ item.date || t('profile.unknown') }} · {{ item.id }}
                <span v-if="item.sizeText && item.sizeText !== '未知大小'"> · {{ item.sizeText }}</span>
              </div>
            </div>
            <template #footer>
              <a-space size="small">
                <a-button text size="small" @click.stop="download(item)">{{ t('video.download') }}</a-button>
                <a-button text size="small" type="danger" @click.stop="handleDeleteWork(item)">{{ t('common.delete') }}</a-button>
              </a-space>
            </template>
          </a-card>
        </template>
        <!-- 可视区域外的轻量占位符 -->
        <div v-else class="virtual-placeholder" :style="{ height: getPlaceholderHeight(item.id) + 'px' }" />
      </div>
    </div>

    <!-- 作品详情模态框 -->
    <a-modal
      v-model:open="detailDialogVisible"
      :title="selectedItem?.title"
      width="70vw"
      @cancel="handleClose"
      class="work-detail-dialog"
      :modal="true"
      :show-close="false"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      align-center
    >
      <!-- 自定义关闭按钮 -->
      <div class="dialog-close-btn" @click="handleClose">
        <CloseOutlined />
      </div>

      <div class="detail-content" :class="{ 'vertical-content': isVerticalVideo }" v-if="selectedItem">
        <div class="detail-left" :class="{ 'vertical-left': isVerticalVideo }">
          <div class="video-container" :class="{ 'vertical-container': isVerticalVideo }">
            <!-- 生成中状态提示 -->
            <div v-if="selectedItem.status === 'PROCESSING' || selectedItem.status === 'PENDING'" class="video-processing-overlay">
              <div class="processing-content">
                <LoadingOutlined class="processing-icon is-loading" style="font-size: 48px" />
                <h3>{{ selectedItem.status === 'PROCESSING' ? t('works.processing') : t('works.queuing') }}</h3>
                <p>{{ t('works.pleaseWait') }}</p>
                <div class="progress-bar-container">
                  <div class="progress-bar-animated"></div>
                </div>
              </div>
            </div>
            <!-- 视频加载失败提示（仅对已完成的作品显示） -->
            <div v-else-if="detailVideoError && selectedItem.status === 'COMPLETED'" class="video-error-overlay">
              <div class="error-content">
                <VideoCameraOutlined class="error-icon" style="font-size: 48px" />
                <h3>{{ t('works.videoLoadFailed') }}</h3>
                <p>{{ t('works.videoFileNotExist') }}</p>
                <div class="error-actions">
                  <a-button type="primary" @click="retryLoadVideo">
                    <ReloadOutlined />
                    {{ t('works.retry') }}
                  </a-button>
                  <a-button type="danger" @click="deleteFailedWork">
                    <DeleteOutlined />
                    {{ t('works.deleteFailedWork') }}
                  </a-button>
                </div>
              </div>
            </div>

            <video
              v-if="selectedItem.type === 'video' && selectedItem.status === 'COMPLETED'"
              ref="detailVideoRef"
              class="detail-video"
              :src="selectedItem.resultUrl || selectedItem.cover"
              :poster="selectedItem.cover !== selectedItem.resultUrl ? selectedItem.cover : ''"
              controls
              @error="onDetailVideoError"
              @loadedmetadata="onDetailVideoLoaded"
            >
              {{ t('profile.browserNotSupport') }}
            </video>
            <!-- 生成中状态显示封面图 -->
            <img
              v-else-if="selectedItem.status === 'PROCESSING' || selectedItem.status === 'PENDING'"
              class="detail-image processing-preview"
              :src="selectedItem.cover || '/images/backgrounds/video-placeholder.jpg'"
              :alt="selectedItem.title"
            />
            <img
              v-else-if="selectedItem.type !== 'video'"
              class="detail-image"
              :src="selectedItem.cover"
              :alt="selectedItem.title"
            />

            <!-- 悬浮操作按钮（仅对已完成的作品显示） -->
            <div class="overlay-actions" v-if="selectedItem.status === 'COMPLETED'">
              <button class="icon-btn" @click="downloadWork" :title="t('common.download')">
                <DownloadOutlined />
              </button>
              <button class="icon-btn delete" @click="deleteFailedWork" :title="t('common.delete')">
                <DeleteOutlined />
              </button>
            </div>
          </div>
        </div>
        
        <div class="detail-right">
          <!-- 用户信息头部 -->
          <div class="detail-header">
            <div class="user-info">
              <div class="avatar">
                <img src="/images/backgrounds/avatar-default.svg" :alt="t('dashboard.userAvatar')" class="avatar-image" />
              </div>
              <div class="username">{{ (selectedItem && selectedItem.username) || t('profile.anonymousUser') }}</div>
            </div>
          </div>

          <!-- 详情标题行 -->
          <div class="detail-title-row">
            <h3>{{ t('works.videoDetail') }}</h3>
            <span class="category-badge">{{ selectedItem.category }}</span>
          </div>

          <!-- 描述区域 -->
          <div class="description-section">
            <div class="section-header">
               <span class="section-label">{{ t('works.description') }}</span>
            </div>
            <p class="description-text">
              {{ getDescription(selectedItem) }}
              <CopyOutlined class="copy-icon" @click="copyPrompt" :title="t('common.copy')" />
            </p>
          </div>

          <!-- 元数据区域 -->
          <div class="metadata-section">
            <div class="metadata-item">
              <span class="label">{{ t('profile.createTime') }}</span>
              <span class="value">{{ selectedItem.createTime }}</span>
            </div>
            <div class="metadata-item">
              <span class="label">{{ t('profile.workId') }}</span>
              <span class="value">{{ selectedItem.taskId }}</span>
            </div>
            <div class="metadata-item" v-if="selectedItem.type !== 'image'">
              <span class="label">{{ t('profile.duration') }}</span>
              <span class="value">{{ formatDuration(selectedItem.duration) || '5s' }}</span>
            </div>
            <div class="metadata-item" v-if="selectedItem.type !== 'image'">
              <span class="label">{{ t('profile.quality') }}</span>
              <span class="value">{{ selectedItem.quality || '1080p' }}</span>
            </div>
            <div class="metadata-item">
              <span class="label">{{ t('profile.aspectRatio') }}</span>
              <span class="value">{{ selectedItem.aspectRatio || '16:9' }}</span>
            </div>
          </div>
        </div>
      </div>
    </a-modal>

        <div class="loading-indicator" v-if="loading">
          <LoadingOutlined class="is-loading" />
          <span>{{ t('common.loading') }}</span>
        </div>
        <div class="finished" v-if="!hasMore && filteredItems.length>0">
          <span>{{ t('works.allLoaded') }}</span>
        </div>
        <a-empty v-if="!LoadingOutlined && filteredItems.length===0" :description="t('works.noContent')" />

        <!-- 回到顶部按钮 -->
        <transition name="fade">
          <div v-show="showBackToTop" class="back-to-top" @click="scrollToTop" :title="t('works.backToTop')">
            <ArrowUpOutlined />
          </div>
        </transition>
      </div>
      </main>

    <!-- 用户菜单下拉（管理员功能） -->
    <Teleport to="body">
      <div v-if="showUserMenu" class="user-menu-teleport" :style="menuStyle">
        <template v-if="userStore.isAdmin">
          <div class="menu-item" @click="goToDashboard">
            <UserOutlined />
            <span>{{ t('profile.dashboard') }}</span>
          </div>
          <div class="menu-item" @click="goToOrders">
            <FileOutlined />
            <span>{{ t('profile.orderManagement') }}</span>
          </div>
          <div class="menu-item" @click="goToMembers">
            <UserOutlined />
            <span>{{ t('profile.memberManagement') }}</span>
          </div>
          <div class="menu-item" @click="goToSettings">
            <SettingOutlined />
            <span>{{ t('profile.systemSettings') }}</span>
          </div>
          <div class="menu-item" @click="goToErrorStats">
            <WarningOutlined />
            <span>{{ $t('nav.errorStats') }}</span>
          </div>
          <div class="menu-item" @click="goToApiManagement">
            <FileOutlined />
            <span>{{ t('nav.apiManagement') }}</span>
          </div>
          <div class="menu-item" @click="goToTaskRecord">
            <FileOutlined />
            <span>{{ t('nav.tasks') }}</span>
          </div>
        </template>
        <!-- 修改密码 -->
        <div class="menu-item" @click.stop="goToChangePassword" style="cursor: pointer;">
          <LockOutlined />
          <span>{{ t('profile.changePassword') }}</span>
        </div>
        <div class="menu-item" @click="logout">
          <UserOutlined />
          <span>{{ t('common.logout') }}</span>
        </div>
      </div>
    </Teleport>
  </div>

</template>

<script setup>
import { ref, onMounted, onActivated, computed, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { UserOutlined, CompassOutlined, FileOutlined, PlayCircleOutlined, PictureOutlined, VideoCameraOutlined, SearchOutlined, LoadingOutlined, ArrowUpOutlined, ReloadOutlined, DeleteOutlined, CopyOutlined, DownloadOutlined, CloseOutlined, SettingOutlined, LockOutlined, WarningOutlined } from '@ant-design/icons-vue'
import { getMyWorks, getWorkDetail, deleteWork, recordDownload, getWorkFileUrl } from '@/api/userWorks'
import { getCurrentUser } from '@/api/auth'
import { useUserStore } from '@/stores/user'
import TopHeader from '@/components/TopHeader.vue'
import SidebarNav from '@/components/SidebarNav.vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()

// 用户菜单状态
const showUserMenu = ref(false)
const topHeaderRef = ref(null)

// 计算用户菜单 Teleport 的位置
const menuStyle = computed(() => {
  const avatarEl = topHeaderRef.value?.avatarRef
  if (!avatarEl || !showUserMenu.value) return {}

  const rect = avatarEl.getBoundingClientRect()
  return {
    position: 'fixed',
    top: `${rect.bottom + 8}px`,
    right: `${window.innerWidth - rect.right}px`,
    zIndex: 99999
  }
})

// 用户信息
const userInfo = ref({
  username: '',
  nickname: '',
  bio: '',
  avatar: '',
  id: '',
  points: 0,
  frozenPoints: 0
})

const activeTab = ref('all')
const dateRange = ref([])
const dateFilter = ref(null)
const category = ref('all')
const resolution = ref(null)
const sortBy = ref(null)
const order = ref('desc')
const keyword = ref('')
const searchKeyword = ref('')
const multiSelect = ref(false)
const selectedIds = ref(new Set())

// 模态框相关状态
const detailDialogVisible = ref(false)
const selectedItem = ref(null)
const activeDetailTab = ref('detail')
const detailVideoError = ref(false)
const detailVideoRef = ref(null)

// 判断是否是竖版视频（9:16）
const isVerticalVideo = computed(() => {
  if (!selectedItem.value) return false
  const ratio = selectedItem.value.aspectRatio
  return ratio === '9:16' || ratio === '9/16' || ratio === '3:4' || ratio === '4:5'
})

const page = ref(1)
const pageSize =  ref(20)
const loading = ref(false)
const hasMore = ref(true)
const items = ref([])
const showBackToTop = ref(false) // 回到顶部按钮显示状态
const failedUrls = ref(new Set()) // 记录加载失败的URL
const pollingIntervalId = ref(null) // 轮询定时器ID
const POLLING_INTERVAL = 120000 // 2分钟轮询间隔

// ===== 虚拟滚动 =====
const contentAreaRef = ref(null)
const visibleItemIds = ref(new Set())
const itemHeightCache = {} // 缓存卡片高度，用于占位符尺寸
const itemElMap = new Map() // id -> DOM element
let virtualObserver = null

// 注册/注销元素的观察
const setItemRef = (el, id) => {
  if (el) {
    itemElMap.set(id, el)
    if (virtualObserver) virtualObserver.observe(el)
  } else {
    const oldEl = itemElMap.get(id)
    if (oldEl && virtualObserver) virtualObserver.unobserve(oldEl)
    itemElMap.delete(id)
  }
}

const isItemVisible = (id) => visibleItemIds.value.has(id)

const getPlaceholderHeight = (id) => itemHeightCache[id] || 250

const setupVirtualObserver = () => {
  if (virtualObserver) virtualObserver.disconnect()

  virtualObserver = new IntersectionObserver(
    (entries) => {
      const next = new Set(visibleItemIds.value)
      let changed = false
      for (const entry of entries) {
        const id = entry.target.dataset.vid
        if (!id) continue
        if (entry.isIntersecting) {
          if (!next.has(id)) { next.add(id); changed = true }
        } else {
          // 离开可视区前缓存高度
          const h = entry.target.offsetHeight
          if (h > 0) itemHeightCache[id] = h
          if (next.has(id)) { next.delete(id); changed = true }
        }
      }
      if (changed) visibleItemIds.value = next
    },
    {
        root: contentAreaRef.value,
        rootMargin: '50% 0px', // 上下 50% 视口高度的缓冲区
        threshold: 0
      }
  )

  // 观察已注册的元素
  itemElMap.forEach(el => virtualObserver.observe(el))
}

// 处理URL，确保相对路径正确
const processUrl = (url) => {
  if (!url) return null
  // data: 协议（Base64 图片等）直接返回，避免被当成相对路径错误加前缀
  if (url.startsWith('data:')) {
    return url
  }
  // 如果已经是完整URL（http/https），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  // 如果是相对路径（以/开头），确保以/开头
  if (url.startsWith('/')) {
    return url
  }
  // 否则添加/前缀
  return '/' + url
}

// 将后端返回的UserWork数据转换为前端需要的格式
const transformWorkData = (work) => {
  const resultUrl = processUrl(work.resultUrl)
  const thumbnailUrl = processUrl(work.thumbnailUrl)
  const isVideoType = work.workType === 'TEXT_TO_VIDEO' || work.workType === 'IMAGE_TO_VIDEO' || work.workType === 'STORYBOARD_VIDEO'
  const cover = thumbnailUrl || resultUrl || '/images/backgrounds/welcome.jpg'
  // thumbnailCover: 用于卡片缩略图，视频类型只用 thumbnailUrl（图片），不回退到 resultUrl（视频文件）
  const thumbnailCover = thumbnailUrl || (isVideoType ? null : resultUrl) || null

  return {
    id: work.id?.toString() || work.taskId || '',
    taskId: work.taskId || work.id?.toString() || '',
    title: work.title || work.prompt || t('common.untitledWork'),
    cover: cover,
    thumbnailCover: thumbnailCover,
    resultUrl: resultUrl || '',
    type: isVideoType ? 'video' : 'image',
    category: work.workType === 'TEXT_TO_VIDEO' ? t('common.textToVideoCategory') : work.workType === 'IMAGE_TO_VIDEO' ? t('common.imageToVideoCategory') : work.workType === 'STORYBOARD_VIDEO' ? t('common.storyboardVideoCategory') : work.workType === 'STORYBOARD_IMAGE' ? t('common.storyboardImageCategory') : t('common.unknownCategory'),
    sizeText: work.fileSize || t('common.unknownSize'),
    createTime: work.createdAt ? new Date(work.createdAt).toLocaleString('zh-CN') : '',
    date: work.createdAt ? new Date(work.createdAt).toLocaleDateString('zh-CN') : '',
    description: work.description || work.prompt || '',
    prompt: work.prompt || '',
    duration: work.duration || work.videoDuration || work.length || '',
    aspectRatio: work.aspectRatio || work.ratio || work.aspect || '',
    quality: work.quality || work.resolution || '',
    username: work.username || work.user?.username || work.creator || work.author || work.owner || t('common.unknownUser'),
    status: work.status || 'COMPLETED',
    uploadedImages: work.uploadedImages || null, // 分镜图阶段用户上传的参考图
    videoReferenceImages: work.videoReferenceImages || null, // 视频阶段用户上传的参考图（分镜视频做同款需要）
    imagePrompt: work.imagePrompt || null, // 分镜图优化后的提示词
    videoPrompt: work.videoPrompt || null, // 视频优化后的提示词
    workType: work.workType || '', // 原始作品类型
  // overlayText 已移除，前端详情不再显示浮动文本
  }
}

// 点击外部关闭用户菜单
const handleClickOutside = (event) => {
  const userAvatar = event.target.closest('.user-avatar')
  const userMenu = event.target.closest('.user-menu-teleport')
  if (!userAvatar && !userMenu) {
    showUserMenu.value = false
  }
}

// 管理员菜单导航
const goToDashboard = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/admin/dashboard')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToOrders = () => {
  showUserMenu.value = false
  router.push('/admin/orders')
}

const goToMembers = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/member-management')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToErrorStats = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/admin/error-statistics')
  }
}

const goToSettings = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/system-settings')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToApiManagement = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/api-management')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToTaskRecord = () => {
  showUserMenu.value = false
  if (userStore.isAdmin) {
    router.push('/generate-task-record')
  } else {
    message.warning(t('profile.insufficientPermission'))
  }
}

const goToChangePassword = () => {
  showUserMenu.value = false
  router.push('/change-password')
}

// 退出登录
const logout = async () => {
  try {
    showUserMenu.value = false
    await userStore.logoutUser()
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    message.success(t('profile.logoutSuccess'))
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    message.error(t('profile.logoutFailed'))
  }
}

const loadList = async () => {
  loading.value = true
  try {
    const response = await getMyWorks({
      page: page.value - 1, // 后端使用0-based分页
      size: pageSize.value
    })

    if (response.data.success) {
      const data = response.data.data || []
      const totalPages = response.data.totalPages || 0
      const currentPage = response.data.currentPage || 0

      // 转换数据格式
      const transformedData = data
        .map(transformWorkData)
        .filter(work => work.status !== 'FAILED' && work.status !== 'DELETED')

      if (page.value === 1) items.value = []
      items.value = items.value.concat(transformedData)
      
      // 使用后端返回的总页数来判断是否还有更多数据
      hasMore.value = currentPage < totalPages - 1
      
      console.log('[MyWorks] 分页信息 - 当前页:', currentPage, '总页数:', totalPages, '是否有更多:', hasMore.value)
      
      // 检查是否有处理中的任务，如果有则启动轮询
      checkAndStartPolling()
    } else {
      throw new Error(response.data.message || t('profile.loadWorksFailed'))
    }
  } catch (error) {
    console.error('加载作品列表失败:', error)
    message.error(t('profile.loadWorksFailed'))
  } finally {
    loading.value = false
  }
}

// 检查是否有处理中的任务，如果有则启动轮询
const checkAndStartPolling = () => {
  const hasProcessingTasks = items.value.some(
    item => item.status === 'PROCESSING' || item.status === 'PENDING'
  )
  
  if (hasProcessingTasks && !pollingIntervalId.value) {
    console.log('[MyWorks] 检测到处理中的任务，启动2分钟轮询')
    startPolling()
  } else if (!hasProcessingTasks && pollingIntervalId.value) {
    console.log('[MyWorks] 没有处理中的任务，停止轮询')
    stopPolling()
  }
}

// 启动轮询
const startPolling = () => {
  if (pollingIntervalId.value) return // 避免重复启动
  
  pollingIntervalId.value = setInterval(async () => {
    console.log('[MyWorks] 执行轮询刷新...')
    // 静默刷新，不显示loading
    try {
      const response = await getMyWorks({
        page: 0,
        size: pageSize.value
      })
      
      if (response.data.success) {
        const data = response.data.data || []
        const transformedData = data
          .map(transformWorkData)
          .filter(work => work.status !== 'FAILED' && work.status !== 'DELETED')
        
        // 更新列表
        items.value = transformedData
        
        // 检查是否还需要继续轮询
        const hasProcessingTasks = transformedData.some(
          item => item.status === 'PROCESSING' || item.status === 'PENDING'
        )
        
        if (!hasProcessingTasks) {
          console.log('[MyWorks] 所有任务已完成，停止轮询')
          stopPolling()
          // 刷新用户积分
          await userStore.fetchCurrentUser()
        }
      }
    } catch (error) {
      console.error('[MyWorks] 轮询刷新失败:', error)
    }
  }, POLLING_INTERVAL)
}

// 停止轮询
const stopPolling = () => {
  if (pollingIntervalId.value) {
    clearInterval(pollingIntervalId.value)
    pollingIntervalId.value = null
    console.log('[MyWorks] 轮询已停止')
  }
}

// 筛选后的作品列表
const filteredItems = computed(() => {
  let filtered = [...items.value]

  // 过滤掉加载失败的作品（但保留 PROCESSING 和 PENDING 状态的作品）
  filtered = filtered.filter(item => {
    // PROCESSING 和 PENDING 状态的作品始终保留，不受 failedUrls 影响
    if (item.status === 'PROCESSING' || item.status === 'PENDING') {
      return true
    }
    const resultUrlFailed = item.resultUrl && failedUrls.value.has(item.resultUrl)
    const coverFailed = item.cover && failedUrls.value.has(item.cover)
    return !resultUrlFailed && !coverFailed
  })

  // 按状态筛选（默认只显示已完成的作品，除非用户选择查看全部）
  // 注释掉状态过滤，允许显示所有作品包括处理中的
  // filtered = filtered.filter(item => item.status === 'COMPLETED')

  // 按日期筛选
  if (dateFilter.value) {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

    filtered = filtered.filter(item => {
      if (!item.createdAt && !item.date) return false

      // 获取作品创建日期
      let itemDate
      if (item.createdAt) {
        itemDate = new Date(item.createdAt)
      } else if (item.date) {
        // 如果只有 date 字符串，尝试解析
        itemDate = new Date(item.date)
      }

      if (!itemDate || isNaN(itemDate.getTime())) return false

      // 重置时间为当天开始
      const itemDay = new Date(itemDate.getFullYear(), itemDate.getMonth(), itemDate.getDate())

      if (dateFilter.value === 'today') {
        // 今天：日期相同
        return itemDay.getTime() === today.getTime()
      } else if (dateFilter.value === 'week') {
        // 本周：过去7天内
        const weekAgo = new Date(today)
        weekAgo.setDate(weekAgo.getDate() - 7)
        return itemDay >= weekAgo && itemDay <= today
      } else if (dateFilter.value === 'month') {
        // 本月：过去30天内
        const monthAgo = new Date(today)
        monthAgo.setDate(monthAgo.getDate() - 30)
        return itemDay >= monthAgo && itemDay <= today
      }

      return true
    })
  }

  // 按类型筛选（全部/视频/图片）
  if (activeTab.value === 'video') {
    filtered = filtered.filter(item => item.type === 'video')
  } else if (activeTab.value === 'image') {
    filtered = filtered.filter(item => item.type === 'image')
  }

  // 按分类筛选
  if (category.value !== 'all') {
    const categoryMap = {
      'text2video': '文生视频',
      'image2video': '图生视频',
      'storyboard': '分镜视频',
      'reference': '参考图'
    }
    const targetCategory = categoryMap[category.value]
    if (targetCategory) {
      filtered = filtered.filter(item => item.category === targetCategory)
    }
  }

  // 按清晰度筛选
  if (resolution.value) {
    filtered = filtered.filter(item => {
      const itemQuality = (item.quality || '').toLowerCase()
      const filterValue = resolution.value.toLowerCase()

      // 映射关系：sd=标清, hd=高清, uhd=超清
      if (filterValue === 'sd') {
        return itemQuality === 'sd' || itemQuality.includes('标清')
      } else if (filterValue === 'hd') {
        return itemQuality === 'hd' || itemQuality.includes('高清')
      } else if (filterValue === 'uhd') {
        return itemQuality === 'uhd' || itemQuality.includes('超清') || itemQuality.includes('4k')
      }
      return false
    })
  }

  // 按宽高比筛选（使用 sortBy 作为比例过滤值）
  if (sortBy.value) {
    const targetRatio = (sortBy.value || '').trim()
    filtered = filtered.filter(item => {
      const ratio = (item.aspectRatio || '').trim()
      return targetRatio && ratio === targetRatio
    })
  }

  // 按关键词筛选（只有点击搜索或回车后才生效）
  if (searchKeyword.value) {
    const keywordLower = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(item =>
      item.title.toLowerCase().includes(keywordLower) ||
      item.id.includes(keywordLower)
    )
  }

  return filtered
})

const reload = () => {
  page.value = 1
  hasMore.value = true
  loadList()
}

// 执行搜索
const doSearch = () => {
  searchKeyword.value = keyword.value
}

// 筛选变化时的处理
const onFilterChange = () => {
  // 筛选是响应式的，不需要额外处理
  console.log('筛选条件变化:', { category: category.value, activeTab: activeTab.value })
}

const loadMore = () => {
  if (loading.value || !hasMore.value) return
  page.value += 1
  loadList()
}

// 滚动监听，触底自动加载更多，控制回到顶部按钮显示
const handleScroll = (event) => {
  const target = event.target
  const scrollTop = target.scrollTop
  const scrollHeight = target.scrollHeight
  const clientHeight = target.clientHeight

  // 控制回到顶部按钮显示（滚动超过300px时显示）
  showBackToTop.value = scrollTop > 300

  // 当滚动到距离底部100px时，自动加载更多
  if (scrollHeight - scrollTop - clientHeight < 100) {
    loadMore()
  }
}

// 滚动到顶部
const scrollToTop = () => {
  const contentArea = document.querySelector('.content-area')
  if (contentArea) {
    contentArea.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  }
}

const openDetail = async (item) => {
  // 优先从后端拉取最新的详情数据，降级为传入的 item
  try {
    const resp = await getWorkDetail(item.id)
    const payload = resp?.data?.data || resp?.data || null
    if (payload) {
      selectedItem.value = transformWorkData(payload)
    } else {
      selectedItem.value = item
    }
  } catch (err) {
    console.warn('获取作品详情失败，使用已有数据：', err)
    selectedItem.value = item
  }
  detailDialogVisible.value = true
}

// 获取作品提示词（优先使用 prompt，其次使用后台 description，最后回退默认文案）
const getDescription = (item) => {
  if (!item) return ''
  const desc = (item.prompt && item.prompt.trim()) ? item.prompt : (item.description && item.description.trim() ? item.description : '')
  if (desc) return desc
  // 回退文案
  return t('profile.noPrompt')
}

// 格式化清晰度显示
const formatQuality = (quality) => {
  if (!quality) return ''
  const q = quality.toUpperCase()
  const qualityMap = {
    'SD': t('works.sd'),
    'HD': t('works.hd'),
    'UHD': t('works.uhd'),
    '4K': t('works.uhd')
  }
  return qualityMap[q] || q
}

// 格式化时长（支持数字秒或字符串），返回类似 "5s" 或原始字符串
const formatDuration = (dur) => {
  if (dur === null || dur === undefined || dur === '') return ''
  if (typeof dur === 'number') return `${dur}s`
  if (typeof dur === 'string') {
    const trimmed = dur.trim()
    if (/^\d+$/.test(trimmed)) return `${trimmed}s`
    return trimmed
  }
  return String(dur)
}

// 关闭模态框
const handleClose = () => {
  detailDialogVisible.value = false
  selectedItem.value = null
  activeDetailTab.value = 'detail'
  detailVideoError.value = false
}

// 详情页视频加载成功
const onDetailVideoLoaded = (event) => {
  console.log('✓ 详情页视频加载成功')
  detailVideoError.value = false
}

// 详情页视频加载失败
const onDetailVideoError = (event) => {
  console.error('❌ 详情页视频加载失败:', event.target?.src)
  detailVideoError.value = true

  // 详细诊断
  const url = event.target?.src
  if (url) {
    console.log('🔍 开始诊断详情页视频加载失败原因...')

    fetch(url, { method: 'HEAD' })
      .then(response => {
        console.log('📊 HTTP 响应状态:', response.status, response.statusText)

        if (response.status === 403) {
          console.error('🔒 403 Forbidden - OSS Bucket 权限问题！')
          console.error('💡 解决方法：')
          console.error('   1. 检查 OSS Bucket 读取权限设置')
          console.error('   2. 后端需要生成签名 URL')
        } else if (response.status === 404) {
          console.error('❌ 404 Not Found - 文件不存在！')
          console.error('💡 可能原因：')
          console.error('   1. OSS 设置了生命周期规则自动删除')
          console.error('   2. 文件被手动删除')
          console.error('   3. 检查 OSS 控制台是否还有该文件')
        } else if (response.ok) {
          console.log('✓ 文件存在但无法播放')
          console.error('💡 可能原因：CORS 配置或视频编码问题')
        }
      })
      .catch(err => console.error('🌐 网络错误:', err.message))
  }
}

// 重试加载视频
const retryLoadVideo = () => {
  detailVideoError.value = false
  if (detailVideoRef.value) {
    detailVideoRef.value.load()
  }
}

// 删除失败的作品
const deleteFailedWork = async () => {
  if (!selectedItem.value) return

  try {
    await new Promise((resolve, reject) => {
      Modal.confirm({
        title: t('works.deleteConfirmTitle'),
        content: t('works.deleteFailedWorkConfirm'),
        okText: t('common.delete'),
        cancelText: t('common.cancel'),
        onOk() { resolve() },
        onCancel() { reject('cancel') }
      })
    })

    // 执行删除
    const itemId = selectedItem.value.id  // 先保存 id，因为 handleClose 会将 selectedItem 设为 null
    console.log('删除作品:', itemId)
    const response = await deleteWork(itemId)

    if (response.data.success) {
      message.success(t('works.deleteSuccess'))

      // 从列表中移除该作品（在关闭详情页之前）
      items.value = items.value.filter(item => item.id !== itemId)

      // 关闭详情页
      handleClose()

      // 或者重新加载列表
      // reload()
    } else {
      throw new Error(response.data.message || t('works.deleteFailed'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除作品失败:', error)
      message.error(error.message || t('works.deleteFailed'))
    }
  }
}

// 创建同款
const createSimilar = (item) => {
  if (!item) {
    message.info(t('works.goToCreate'))
    return
  }
  
  // 根据作品类别跳转到对应的创建页面，并携带参数
  // 注意：不传递 taskId，因为"做同款"是创建新任务，不是继续原任务
  const query = {
    prompt: item.prompt || '',
    aspectRatio: item.aspectRatio || '',
    duration: item.duration || '',
    hdMode: item.quality === 'HD' ? 'true' : 'false'
  }
  
  // 添加参考图（图生视频需要，分镜图/分镜视频的 cover 是生成结果不传递到 referenceImage）
  if (item.category !== '分镜图' && item.category !== '分镜视频' && item.cover && item.cover !== '/images/backgrounds/welcome.jpg') {
    query.referenceImage = item.cover
  }
  
  console.log('[做同款] 跳转参数:', query, 'category:', item.category, 'workType:', item.workType)
  
  if (item.category === '文生视频') {
    router.push({ path: '/text-to-video/create', query })
  } else if (item.category === '图生视频') {
    router.push({ path: '/image-to-video/create', query })
  } else if (item.category === '分镜图' || item.workType === 'STORYBOARD_IMAGE') {
    // 分镜图做同款：进入 Step 1（生成分镜图），使用 imagePrompt
    query.step = 'image'
    if (item.imagePrompt) {
      query.imagePrompt = item.imagePrompt
    }
    // 传递分镜图阶段的参考图
    if (item.uploadedImages) {
      query.uploadedImages = item.uploadedImages
      console.log('[做同款-分镜图] 传递参考图:', item.uploadedImages)
    } else {
      console.log('[做同款-分镜图] 无参考图数据, item:', item)
    }
    router.push({ path: '/storyboard-video/create', query })
  } else if (item.category === '分镜视频') {
    // 分镜视频做同款：进入 Step 2（生成视频），携带已生成的分镜图和视频参考图
    query.step = 'video'
    // cover 是分镜图（thumbnailUrl），传递给 Step 2 作为分镜图
    if (item.cover && item.cover !== '/images/backgrounds/welcome.jpg') {
      query.storyboardImage = item.cover
    }
    // 传递视频提示词（videoPrompt）
    if (item.videoPrompt) {
      query.prompt = item.videoPrompt
    } else if (item.imagePrompt) {
      query.prompt = item.imagePrompt
    } else if (item.prompt) {
      query.prompt = item.prompt
    }
    // 传递视频阶段的参考图（videoReferenceImages），不是分镜图阶段的参考图
    if (item.videoReferenceImages) {
      query.videoReferenceImages = item.videoReferenceImages
    }
    router.push({ path: '/storyboard-video/create', query })
  } else {
    // 默认跳转到文生视频
    router.push({ path: '/text-to-video/create', query })
  }
  
  message.success(t('works.createSimilarInfo', { title: item.title }))
}

// 生视频 - 使用分镜图直接生成视频
const goToGenerateVideo = (item) => {
  if (!item) return
  
  // 跳转到图生视频创作页面，传递分镜图作为参考图
  const query = {
    aspectRatio: item.aspectRatio || '',
    duration: item.duration || '',
    hdMode: item.quality === 'HD' ? 'true' : 'false',
    _t: Date.now() // 添加时间戳确保路由参数变化被检测到
  }
  
  // 使用分镜图作为参考图
  if (item.cover && item.cover !== '/images/backgrounds/welcome.jpg') {
    query.referenceImage = item.cover
  } else if (item.resultUrl) {
    query.referenceImage = item.resultUrl
  }
  
  // 传递视频提示词：优先使用 videoPrompt，其次 imagePrompt，最后 prompt
  if (item.videoPrompt) {
    query.prompt = item.videoPrompt
  } else if (item.imagePrompt) {
    query.prompt = item.imagePrompt
  } else if (item.prompt) {
    query.prompt = item.prompt
  }
  
  console.log('[生视频] 跳转到图生视频页面，参数:', query)
  router.push({ path: '/image-to-video/create', query })
  message.success(t('works.readyToGenerateVideo'))
}

const download = async (item) => {
  try {
    // 检查是否有结果URL
    if (!item.resultUrl) {
      message.error(t('works.noDownloadUrl'))
      return
    }

    message.info(t('works.downloadStart', { title: item.title }))

    // 记录下载次数
    try {
      await recordDownload(item.id)
    } catch (err) {
      console.warn('记录下载次数失败:', err)
    }

    // 使用兼容 Safari 的下载工具
    const videoUrl = item.resultUrl
    console.log('下载URL:', videoUrl)
    
    try {
      const { downloadFile } = await import('@/utils/download')
      const filename = `${item.title || 'work'}_${Date.now()}${item.type === 'video' ? '.mp4' : '.png'}`
      const mimeType = item.type === 'video' ? 'video/mp4' : 'image/png'
      
      const success = await downloadFile(videoUrl, filename, mimeType)
      if (success) {
        message.success(t('works.downloadComplete'))
        return
      }
    } catch (directError) {
      console.warn('直接下载失败，尝试后端代理:', directError)
    }

    // 备用方案：使用后端代理
    const downloadUrl = getWorkFileUrl(item.id, true)
    const token = localStorage.getItem('token')
    
    console.log('开始下载:', downloadUrl)
    
    // 使用 fetch 下载文件（后端代理模式）
    const response = await fetch(downloadUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('响应状态:', response.status)

    if (!response.ok) {
      const errorText = await response.text()
      console.error('下载失败:', errorText)
      throw new Error(`下载失败: ${response.status}`)
    }

    // 获取文件内容
    const blob = await response.blob()
    console.log('文件大小:', blob.size, 'bytes')
    
    if (blob.size === 0) {
      throw new Error('文件内容为空，可能URL已过期')
    }
    
    // 从响应头获取文件名
    const contentDisposition = response.headers.get('content-disposition')
    let filename = item.title || 'work'
    
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, '').replace(/%20/g, ' '))
      }
    }
    
    // 如果没有扩展名，根据类型添加
    if (!filename.includes('.')) {
      filename += item.type === 'video' ? '.mp4' : '.png'
    }
    
    console.log('下载文件名:', filename)
    
    // 使用兼容工具下载 blob
    const blobUrl = window.URL.createObjectURL(blob)
    const { downloadFile } = await import('@/utils/download')
    await downloadFile(blobUrl, filename, item.type === 'video' ? 'video/mp4' : 'image/png')
    
    // 延迟释放 blob URL
    setTimeout(() => window.URL.revokeObjectURL(blobUrl), 1000)

    message.success(t('works.downloadComplete'))

  } catch (error) {
    console.error('下载作品失败:', error)
    message.error(error.message || t('works.downloadFailed'))
  }
}

// 删除单个作品
const handleDeleteWork = async (item) => {
  try {
    await new Promise((resolve, reject) => {
      Modal.confirm({
        title: t('works.deleteConfirmTitle'),
        content: t('works.deleteWorkConfirm'),
        okText: t('common.delete'),
        cancelText: t('common.cancel'),
        onOk() { resolve() },
        onCancel() { reject('cancel') }
      })
    })
    
    // 执行删除
    const response = await deleteWork(item.id)
    if (response.data.success) {
      message.success(t('works.deleteSuccess'))
      // 从列表中移除
      items.value = items.value.filter(i => i.id !== item.id)
    } else {
      throw new Error(response.data.message || t('works.deleteFailed'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除作品失败:', error)
      message.error(error.message || t('works.deleteFailed'))
    }
  }
}

const toggleSelect = (id) => {
  const next = new Set(selectedIds.value)
  if (next.has(id)) next.delete(id)
  else next.add(id)
  selectedIds.value = next
}

// 全选/取消全选
const isAllSelected = computed(() => {
  if (filteredItems.value.length === 0) return false
  return filteredItems.value.every(item => selectedIds.value.has(item.id))
})

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    // 取消全选
    selectedIds.value = new Set()
    multiSelect.value = false
  } else {
    // 全选
    multiSelect.value = true
    selectedIds.value = new Set(filteredItems.value.map(item => item.id))
  }
}

const bulkDownload = async () => {
  if (selectedIds.value.size === 0) {
    message.warning(t('works.noItemsSelected'))
    return
  }

  message.success(t('works.bulkDownloadStart', { count: selectedIds.value.size }))

  // 获取选中的作品
  const selectedItems = items.value.filter(item => selectedIds.value.has(item.id))

  // 逐个下载（避免浏览器阻止弹窗）
  for (const item of selectedItems) {
    try {
      await download(item)
      // 延迟一下，避免浏览器阻止
      await new Promise(resolve => setTimeout(resolve, 500))
    } catch (error) {
      console.error(`下载作品 ${item.id} 失败:`, error)
    }
  }

  message.success(t('works.bulkDownloadComplete'))
}

const bulkDelete = async () => {
  try {
    await new Promise((resolve, reject) => {
      Modal.confirm({
        title: t('works.deleteConfirmTitle'),
        content: t('works.bulkDeleteConfirm', { count: selectedIds.value.size }),
        okText: t('common.delete'),
        cancelText: t('common.cancel'),
        onOk() { resolve() },
        onCancel() { reject('cancel') }
      })
    })
    message.success(t('works.bulkDeleteSuccess'))
    selectedIds.value = new Set()
  } catch (_) {}
}

// 导航方法
const goToProfile = () => {
  console.log('导航到个人主页')
  router.push('/profile')
}

const goToSubscription = () => {
  console.log('导航到会员订阅')
  router.push('/subscription')
}

const goToTextToVideo = () => {
  console.log('导航到文生视频创作')
  router.push('/text-to-video/create')
}

const goToImageToVideo = () => {
  console.log('导航到图生视频创作')
  router.push('/image-to-video/create')
}

const goToStoryboardVideo = () => {
  console.log('导航到分镜视频创作')
  router.push('/storyboard-video/create')
}

// 重置筛选器
const resetFilters = () => {
  dateFilter.value = null
  category.value = 'all'
  resolution.value = null
  sortBy.value = null
  keyword.value = ''
  searchKeyword.value = ''
  message.success(t('works.filtersReset'))
}

// 视频加载元数据后，跳转到第一帧（但不播放）
const onVideoLoaded = (event) => {
  const video = event.target
  console.log('✓ 视频加载成功:', video.src)
  console.log('视频信息:', {
    duration: video.duration,
    videoWidth: video.videoWidth,
    videoHeight: video.videoHeight,
    readyState: video.readyState
  })

  if (video && video.duration) {
    // 跳转到第一帧（0秒）
    video.currentTime = 0.1
    // 确保视频不播放
    video.pause()
  }
}

// 复制提示词
const copyPrompt = async () => {
  const prompt = getDescription(selectedItem.value)
  if (!prompt || prompt === t('profile.noPrompt')) return
  
  try {
    await navigator.clipboard.writeText(prompt)
    message.success(t('common.copySuccess'))
  } catch (err) {
    console.error('复制失败:', err)
    message.error(t('common.copyFailed'))
  }
}

// 下载当前作品
const downloadWork = () => {
  if (selectedItem.value) {
    download(selectedItem.value)
  }
}

// 视频加载失败处理
const onVideoError = (event) => {
  const video = event.target
  const url = video.src
  console.error('❌ 视频加载失败:', url)
  console.error('错误详情:', event)

  // 记录失败的URL
  failedUrls.value.add(url)

  // 详细诊断 - 测试视频 URL 是否可访问
  console.log('🔍 开始诊断视频加载失败原因...')

  // 方法1: 使用 fetch 获取详细错误
  fetch(url, { method: 'HEAD' })
    .then(response => {
      console.log('📊 HTTP 响应状态:', response.status, response.statusText)
      console.log('📊 响应头:', [...response.headers.entries()])

      if (response.status === 403) {
        console.error('🔒 403 Forbidden - OSS Bucket 权限问题！')
        console.error('💡 可能原因：')
        console.error('   1. Bucket 从"公共读"改为"私有"')
        console.error('   2. 需要使用签名 URL 访问')
        console.error('   3. IP 白名单限制')
      } else if (response.status === 404) {
        console.error('❌ 404 Not Found - 文件不存在！')
        console.error('💡 可能原因：')
        console.error('   1. 文件被删除（手动或生命周期规则）')
        console.error('   2. 文件路径变化')
        console.error('   3. URL 格式错误')
      } else if (response.ok) {
        console.log('✓ HTTP 状态正常，可能是 CORS 或视频编码问题')
        console.error('💡 可能原因：')
        console.error('   1. OSS CORS 配置缺失或错误')
        console.error('   2. 视频编码格式浏览器不支持')
      }
    })
    .catch(err => {
      console.error('🌐 网络错误:', err.message)
      console.error('💡 可能原因：')
      console.error('   1. 网络连接问题')
      console.error('   2. DNS 解析失败')
      console.error('   3. 阿里云账户欠费')
    })

  // 方法2: 使用 Image 对象测试（绕过 CORS）
  const testImg = new Image()
  testImg.onload = () => console.log('✓ URL 可访问（使用 Image 测试）')
  testImg.onerror = () => console.error('✗ URL 不可访问（使用 Image 测试）')
  testImg.src = url

  // 隐藏video元素
  if (video) {
    video.style.display = 'none'

    const thumbContainer = video.parentElement
    const existingImg = thumbContainer.querySelector('.fallback-cover-image')
    const placeholder = thumbContainer.querySelector('.work-placeholder')
    const coverUrl = video.getAttribute('data-cover')

    // 如果有独立的封面图（不同于视频URL），尝试显示封面
    if (coverUrl && coverUrl !== url && coverUrl !== '' && !existingImg) {
      console.log('🔄 视频加载失败，尝试使用独立封面图:', coverUrl)
      const img = document.createElement('img')
      img.className = 'fallback-cover-image work-thumbnail-video'
      img.src = coverUrl
      img.alt = '封面图'
      img.style.cssText = 'position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover;'
      img.onerror = () => {
        console.error('❌ 封面图也加载失败:', coverUrl)
        img.style.display = 'none'
        showPlaceholder(thumbContainer, placeholder)
      }
      thumbContainer.appendChild(img)
    } else {
      // 没有独立封面，直接显示占位符
      console.warn('⚠️ 没有独立封面图，显示占位符')
      showPlaceholder(thumbContainer, placeholder)
    }
  }
}

// 显示占位符的辅助函数
const showPlaceholder = (container, existingPlaceholder) => {
  if (!existingPlaceholder) {
    const div = document.createElement('div')
    div.className = 'work-placeholder'
    div.innerHTML = `
      <svg class="el-icon" style="width: 1em; height: 1em; font-size: 32px; margin-bottom: 8px;">
        <use href="#icon-video-play"></use>
      </svg>
      <div class="placeholder-text" style="font-size: 13px; color: #999;">视频加载失败</div>
      <div class="placeholder-text" style="font-size: 11px; color: #666; margin-top: 4px;">文件可能不存在</div>
    `
    div.style.cssText = 'position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; flex-direction: column; align-items: center; justify-content: center;'
    container.appendChild(div)
  } else {
    existingPlaceholder.style.display = 'flex'
  }
}

// 图片加载失败处理
const onImageError = (event) => {
  const img = event.target
  const url = img.src
  console.error('❌ 图片加载失败:', url)
  console.error('错误详情:', event)

  // 记录失败的URL
  failedUrls.value.add(url)

  // 测试图片 URL 是否可访问 - 使用正常 GET 请求检查
  fetch(url, { method: 'GET' })
    .then(response => {
      if (response.ok) {
        console.log('✓ 图片文件存在但浏览器无法加载，可能是 CORS 或格式问题')
      } else {
        console.error(`✗ HTTP ${response.status}: ${response.statusText} - 文件不存在或无权限`)
      }
    })
    .catch(err => {
      console.error('✗ 网络错误或文件不存在:', err.message)
    })

  // 隐藏图片，显示占位符
  if (img) {
    img.style.display = 'none'
    // 创建或显示占位符（包含完整的图标和文字）
    const placeholder = img.parentElement.querySelector('.work-placeholder')
    if (!placeholder) {
      const div = document.createElement('div')
      div.className = 'work-placeholder'
      div.innerHTML = `
        <svg class="el-icon" style="width: 1em; height: 1em; font-size: 24px;">
          <use href="#icon-video-play"></use>
        </svg>
        <div class="placeholder-text">加载失败</div>
      `
      img.parentElement.appendChild(div)
    } else {
      placeholder.style.display = 'flex'
    }
  }
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await getCurrentUser()
    console.log('获取用户信息响应:', response)
    if (response && response.data && response.data.success && response.data.data) {
      const user = response.data.data
      console.log('用户数据:', user)
      userInfo.value = {
        username: user.username || '',
        nickname: user.nickname || user.username || '',
        bio: user.bio || '',
        avatar: user.avatar || '',
        id: user.id ? String(user.id) : '',
        points: user.points || 0,
        frozenPoints: user.frozenPoints || 0
      }
      console.log('设置后的用户信息:', userInfo.value)
    } else {
      console.error('获取用户信息失败:', response?.data?.message || '未知错误')
      message.error(t('profile.loadUserInfoFailed'))
    }
  } catch (error) {
    // 401错误由axios拦截器处理，不重复提示
    if (error.response?.status === 401) {
      return
    }
    console.error('加载用户信息失败:', error)
    message.error(t('profile.loadUserInfoFailed') + ': ' + (error.message || t('common.unknownError')))
  }
}

onMounted(async () => {
  // #region agent log
  fetch('http://127.0.0.1:7243/ingest/7d01a34a-7181-4a5e-9962-62bb50420571',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'MyWorks.vue:onMounted:entry',message:'MyWorks onMounted start',data:{hasToken:!!localStorage.getItem('token'),isAuthenticated:userStore.user!==null},timestamp:Date.now(),sessionId:'debug-session',hypothesisId:'H-C'})}).catch(()=>{});
  // #endregion
  try {
    // 强制刷新用户信息，确保获取管理员修改后的最新数据
    await userStore.fetchCurrentUser()
    // #region agent log
    fetch('http://127.0.0.1:7243/ingest/7d01a34a-7181-4a5e-9962-62bb50420571',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'MyWorks.vue:onMounted:afterFetch',message:'MyWorks after fetchCurrentUser',data:{hasToken:!!localStorage.getItem('token'),userExists:userStore.user!==null},timestamp:Date.now(),sessionId:'debug-session',hypothesisId:'H-C'})}).catch(()=>{});
    // #endregion
    loadUserInfo()
    loadList()
    // 数据加载后初始化虚拟滚动观察器
    nextTick(() => setupVirtualObserver())
  } catch(e) {
    // #region agent log
    fetch('http://127.0.0.1:7243/ingest/7d01a34a-7181-4a5e-9962-62bb50420571',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'MyWorks.vue:onMounted:error',message:'MyWorks onMounted error',data:{error:e?.message||String(e)},timestamp:Date.now(),sessionId:'debug-session',hypothesisId:'H-C'})}).catch(()=>{});
    // #endregion
  }
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  // 清理轮询定时器
  stopPolling()
  // 清理虚拟滚动观察器
  if (virtualObserver) {
    virtualObserver.disconnect()
    virtualObserver = null
  }
  itemElMap.clear()
})

// 当页面被激活时（从其他页面返回时）刷新列表
onActivated(() => {
  // 重置分页并重新加载
  page.value = 1
  items.value = []
  loadUserInfo()
  loadList()
})
</script>

<style scoped>
/* 图片懒加载样式 */
.lazy-LoadingOutlined {
  background: linear-gradient(90deg, var(--bg-surface) 25%, var(--bg-overlay) 50%, var(--bg-surface) 75%);
  background-size: 200% 100%;
  animation: lazy-shimmer 1.5s infinite;
}

.lazy-loaded {
  animation: lazy-fade-in 0.3s ease-in;
}

.lazy-error {
  background: var(--bg-surface);
}

@keyframes lazy-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

@keyframes lazy-fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}

.works-page {
  height: 100vh;
  background: var(--bg-base);
  color: var(--text-primary);
  display: flex;
  font-family: var(--font-sans);
  margin: 0;
  padding: 0;
  width: 100%;
  position: relative;
  overflow: hidden;
}

/* 页面背景效果已由全局 App.vue 统一处理 */

/* 左侧导航栏 */
.sidebar {
  width: var(--sidebar-width) !important;
  background: var(--bg-elevated) !important;
  padding: var(--space-6) 0 !important;
  border-right: 1px solid var(--border-subtle) !important;
  flex-shrink: 0 !important;
  z-index: var(--z-dropdown) !important;
  display: block !important;
  position: relative !important;
}

.logo {
  padding: 0 var(--space-6) var(--space-8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo img {
  height: 40px;
  width: auto;
}

.nav-menu, .tools-menu {
  padding: 0 var(--space-6);
}

.nav-item {
  display: flex;
  align-items: center;
  padding: var(--space-3) var(--space-4);
  margin-bottom: var(--space-1);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: var(--transition-all);
  position: relative;
}

.nav-item:hover {
  background: var(--bg-hover);
}

.nav-item.active {
  background: var(--primary-glow-light);
  color: var(--primary-400);
}

.nav-item .anticon {
  margin-right: var(--space-3);
  font-size: var(--text-xl);
}

.nav-item span {
  font-size: var(--text-sm);
  flex: 1;
}

.sora-tag {
  margin-left: var(--space-2);
  font-size: 10px;
  padding: 2px var(--space-1);
}

.divider {
  margin: var(--space-8) var(--space-5) var(--space-5);
  padding: 0 var(--space-4);
  color: var(--text-disabled);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}


/* 用户菜单样式（右上角头像下拉） */
.user-menu-teleport {
  background: var(--bg-surface);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-md);
  min-width: 160px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: var(--space-3) var(--space-4);
  cursor: pointer;
  transition: var(--transition-colors);
  color: var(--text-primary);
  font-size: var(--text-sm);
}

.menu-item:hover {
  background: var(--bg-hover);
}

.menu-item .anticon {
  margin-right: var(--space-2);
  font-size: var(--text-base);
}

.menu-item:not(:last-child) {
  border-bottom: 1px solid var(--border-default);
}

.settings-icon {
  cursor: pointer;
  color: var(--text-tertiary);
  font-size: var(--text-xl);
}

.settings-icon:hover {
  color: var(--text-primary);
}

/* 内容区域 */
.content-area {
  flex: 1;
  padding: var(--space-5) var(--space-6);
  overflow-y: auto;
  overflow-x: hidden;
  scroll-behavior: smooth;
}

/* 自定义滚动条样式 - 更明显美观的滚动条 */
.content-area::-webkit-scrollbar {
  width: 12px;
}

.content-area::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.03);
  border-radius: var(--radius-sm);
  margin: var(--space-1) 0;
}

.content-area::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, var(--primary-500) 0%, var(--primary-600) 100%);
  border-radius: var(--radius-sm);
  transition: var(--transition-all);
  border: 2px solid rgba(255, 255, 255, 0.03);
}

.content-area::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, var(--primary-600) 0%, var(--primary-700) 100%);
  border-color: rgba(255, 255, 255, 0.02);
  box-shadow: var(--glow-primary);
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-1) 0 var(--space-1);
}

.works-tab-bar {
  display: inline-flex;
  align-items: center;
  gap: var(--space-2);
}

.works-tab-item {
  width: 163px;
  height: 44px;
  border-radius: 14px;
  border: 2px solid transparent;
  background: var(--bg-surface);
  color: var(--text-secondary);
  font-size: var(--text-sm);
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 var(--space-4);
  transition: all 0.25s ease;
  outline: none;
  white-space: nowrap;
}

.works-tab-item:hover {
  background: var(--primary-50);
  color: var(--primary-600);
  border-color: var(--primary-200);
}

.works-tab-item.active {
  background: var(--gradient-brand);
  color: #fff;
  border-color: transparent;
  box-shadow: 0 4px 16px rgba(124, 58, 237, 0.25);
  font-weight: 600;
}

.works-tab-item:active {
  transform: scale(0.97);
}
.filters { margin-left: var(--space-2); }

/* ===== Filter Bar — Bold Chip Style ===== */
.filters-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  margin-bottom: var(--space-4);
  background: var(--bg-surface);
  border-radius: 16px;
  border: 1px solid var(--border-subtle);
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.04);
  gap: 12px;
}

.filters-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

/* Filter Chip — 胶囊筛选器 */
.filter-chip {
  display: flex;
  align-items: center;
  padding: 4px 6px 4px 6px;
  background: var(--bg-root);
  border: 1.5px solid var(--border-default);
  border-radius: 24px;
  transition: all 0.25s ease;
  cursor: pointer;
}

.filter-chip:hover {
  border-color: var(--primary-300);
  background: var(--primary-50);
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.1);
}

/* 下拉框在 chip 内的样式 */
.filter-chip :deep(.ant-select) {
  width: auto !important;
  min-width: 70px;
}

.filter-chip :deep(.ant-select-selector) {
  height: 28px !important;
  padding: 0 24px 0 10px !important;
  border-radius: 12px !important;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  min-height: unset !important;
}

.filter-chip :deep(.ant-select-selection-item) {
  color: var(--primary-600) !important;
  font-size: 13px !important;
  font-weight: 600 !important;
  line-height: 28px !important;
}

.filter-chip :deep(.ant-select-selection-placeholder) {
  color: var(--text-secondary) !important;
  font-size: 13px !important;
  font-weight: 500 !important;
  line-height: 28px !important;
  opacity: 1 !important;
}

.filter-chip :deep(.ant-select-arrow) {
  color: var(--primary-400) !important;
  font-size: 10px !important;
  right: 8px !important;
}

/* Reset Button */
.filter-reset-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 6px 14px;
  border-radius: 24px;
  border: 1.5px solid var(--error-400);
  background: rgba(239, 68, 68, 0.06);
  color: var(--error-500);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.25s ease;
  white-space: nowrap;
}

.filter-reset-btn:hover {
  background: var(--error-500);
  color: #fff;
  border-color: var(--error-500);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.25);
  transform: translateY(-1px);
}

/* Search Box */
.filters-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 16px;
  background: var(--bg-root);
  border: 1.5px solid var(--border-default);
  border-radius: 24px;
  transition: all 0.25s ease;
  min-width: 200px;
}

.search-box:focus-within {
  border-color: var(--primary-400);
  box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
  background: var(--bg-surface);
}

.search-box-icon {
  color: var(--text-tertiary);
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s ease;
  flex-shrink: 0;
}

.search-box:focus-within .search-box-icon {
  color: var(--primary-500);
}

.search-box :deep(.ant-input) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  color: var(--text-primary) !important;
  font-size: 13px !important;
  padding: 0 !important;
  height: 24px !important;
  line-height: 24px !important;
}

.search-box :deep(.ant-input::placeholder) {
  color: var(--text-tertiary) !important;
  font-size: 13px !important;
}

/* 全局下拉框中的图标颜色 */
.filters-bar :deep(.anticon) {
  font-size: var(--text-xs);
}

.select-row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0 12px;
}
.works-grid { 
  column-count: 5;
  column-gap: var(--space-4);
  margin-top: var(--space-3);
}
.works-grid-item {
  break-inside: avoid;
  margin-bottom: var(--space-4);
}

/* 虚拟滚动占位符 */
.virtual-placeholder {
  background: var(--bg-surface);
  border-radius: 14px;
  border: 1px solid var(--border-subtle);
}
.work-card { 
  width: 100%;
}
.thumb { 
  position: relative; 
  width: 100%; 
  overflow: hidden; 
  border-radius: 14px; 
  cursor: pointer;
  min-height: 120px;
}
.thumb img { width: 100%; display: block; object-fit: cover; border-radius: 14px; }
.work-thumbnail-video {
  width: 100%;
  display: block;
  object-fit: cover;
  border-radius: 14px;
  pointer-events: none;
}
.work-placeholder {
  width: 100%;
  min-height: 180px;
  background: linear-gradient(135deg, var(--primary-50), rgba(236, 72, 153, 0.06));
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-tertiary);
  font-size: var(--text-2xl);
  gap: var(--space-2);
  border-radius: 14px;
  border: 2px dashed var(--primary-200);
}

.placeholder-text {
  font-size: var(--text-xs);
  color: var(--text-disabled);
}

/* 动态进度条 */
.progress-bar-container {
  width: 60%;
  height: 4px;
  background: var(--bg-active);
  border-radius: 2px;
  overflow: hidden;
  margin-top: var(--space-3);
}

.progress-bar-animated {
  width: 30%;
  height: 100%;
  background: linear-gradient(90deg, var(--primary-400), var(--secondary-400), var(--accent-400), var(--primary-400));
  background-size: 300% 100%;
  border-radius: 2px;
  animation: progress-move 1.5s ease-in-out infinite, progress-gradient 2s linear infinite;
}

@keyframes progress-move {
  0% {
    transform: translateX(-100%);
  }
  50% {
    transform: translateX(233%);
  }
  100% {
    transform: translateX(-100%);
  }
}

@keyframes progress-gradient {
  0% {
    background-position: 0% 50%;
  }
  100% {
    background-position: 200% 50%;
  }
}

/* 生成中/排队中状态覆盖层 */
.processing-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(124, 58, 237, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 5;
  border-radius: 14px;
  backdrop-filter: blur(4px);
}

.processing-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-2);
  padding: var(--space-5);
}

.processing-icon {
  font-size: var(--text-4xl);
  color: var(--primary-500);
}

.processing-text {
  font-size: var(--text-sm);
  color: var(--text-primary);
  font-weight: var(--font-medium);
}

.work-placeholder.is-processing {
  background: rgba(0, 0, 0, 0.5);
}
.checker { position: absolute; left: var(--space-1); top: var(--space-1); }

/* 鼠标悬停时显示的按钮容器 */
.hover-buttons-container {
  position: absolute;
  left: 0;
  right: 0;
  bottom: var(--space-1);
  display: flex;
  justify-content: space-between;
  padding: 0 var(--space-1);
  opacity: 0;
  transform: translateY(10px);
  transition: var(--transition-all);
  z-index: 10;
}

.thumb:hover .hover-buttons-container {
  opacity: 1;
  transform: translateY(0);
}

/* 鼠标悬停时显示的做同款按钮 */
.hover-create-btn {
  transition: var(--transition-all);
}

.hover-create-btn.left {
  /* 左下角 */
}

.hover-create-btn.right {
  /* 右下角 */
}

.thumb:hover .hover-create-btn {
  opacity: 1;
  transform: translateY(0);
}

.hover-create-btn .ant-btn {
  background: var(--gradient-cool) !important;
  border: none;
  backdrop-filter: blur(8px);
  box-shadow: 0 4px 16px rgba(124, 58, 237, 0.3);
  border-radius: 10px;
  color: #fff !important;
}

.hover-create-btn .ant-btn:hover {
  box-shadow: 0 6px 24px rgba(124, 58, 237, 0.4);
  transform: scale(1.05);
}

/* 生视频按钮样式 */
.hover-create-btn.right .ant-btn {
  background: var(--gradient-fresh) !important;
  box-shadow: 0 4px 16px rgba(16, 185, 129, 0.3);
}

.hover-create-btn.right .ant-btn:hover {
  box-shadow: 0 6px 24px rgba(16, 185, 129, 0.4);
}
.work-card.selected .thumb::after {
  content: '';
  position: absolute;
  inset: 0;
  border: 3px solid var(--primary-400);
  border-radius: 14px;
  box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.15) inset;
}
.meta { margin-top: var(--space-2); }
.title { font-weight: var(--font-semibold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.sub {
  color: var(--text-tertiary);
  font-size: var(--text-xs);
  margin-top: var(--space-1);
  display: flex;
  align-items: center;
  gap: var(--space-1);
  flex-wrap: wrap;
}

/* 清晰度标签样式 */
.quality-badge {
  display: inline-block;
  padding: 2px var(--space-1);
  border-radius: var(--space-1);
  font-size: 11px;
  font-weight: var(--font-medium);
  margin: 0 2px;
}

.quality-sd {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.12), rgba(6, 182, 212, 0.08));
  color: var(--accent-600);
  border: 1px solid rgba(16, 185, 129, 0.3);
  font-weight: 600;
}

.quality-hd {
  background: linear-gradient(135deg, rgba(124, 58, 237, 0.12), rgba(236, 72, 153, 0.08));
  color: var(--primary-600);
  border: 1px solid rgba(124, 58, 237, 0.3);
  font-weight: 600;
}

.quality-uhd, .quality-4k {
  background: linear-gradient(135deg, rgba(245, 158, 11, 0.12), rgba(249, 115, 22, 0.08));
  color: var(--warning-600);
  border: 1px solid rgba(245, 158, 11, 0.3);
  font-weight: 600;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  padding: var(--space-5) 0;
  margin: var(--space-5) 0;
  color: var(--primary-500);
  font-size: var(--text-sm);
}

.loading-indicator .anticon {
  font-size: var(--text-lg);
}

/* 让卡片焕然一新 — Bold Card */
:deep(.work-card.ant-card) {
  background-color: var(--bg-surface);
  border: 2px solid transparent;
  border-radius: 16px;
  color: var(--text-secondary);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 12px rgba(124, 58, 237, 0.06);
  overflow: hidden;
}
:deep(.work-card.ant-card:hover) {
  transform: translateY(-6px) scale(1.01);
  border-color: var(--primary-300);
  box-shadow: 0 12px 40px rgba(124, 58, 237, 0.18), 0 4px 12px rgba(236, 72, 153, 0.1);
}
:deep(.work-card .ant-card-body) {
  background-color: var(--bg-surface);
}
:deep(.work-card .ant-card-actions) {
  background-color: var(--bg-surface);
  border-top: 1px solid var(--border-subtle);
}

/* 模态框样式 */
:deep(.work-detail-dialog) {
  --el-dialog-margin-top: 5vh;
  --el-dialog-bg-color: transparent;
  --el-dialog-border-radius: var(--radius-lg);
}

:deep(.work-detail-dialog .ant-modal) {
  background: transparent !important;
  box-shadow: none !important;
  border: none !important;
  margin: 0 auto;
  max-width: 95vw;
}

:deep(.work-detail-dialog .ant-modal-header) {
  display: none !important;
}

:deep(.work-detail-dialog .ant-modal-body) {
  padding: 0 !important;
  background: transparent !important;
  position: relative;
}

/* 遮罩层样式 */
:deep(.ant-modal-mask) {
  background-color: rgba(0, 0, 0, 0.85) !important;
  backdrop-filter: blur(8px);
}

/* 自定义关闭按钮 */
.dialog-close-btn {
  position: absolute;
  top: -50px;
  right: 0;
  width: 40px;
  height: 40px;
  border-radius: var(--radius-full);
  background: var(--bg-surface);
  border: 2px solid var(--primary-200);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.25s ease;
  color: var(--text-secondary);
  font-size: var(--text-lg);
  z-index: var(--z-dropdown);
  box-shadow: 0 4px 16px rgba(124, 58, 237, 0.15);
}

.dialog-close-btn:hover {
  background: var(--primary-500);
  border-color: var(--primary-500);
  color: #fff;
  transform: scale(1.1);
}

.detail-content {
  display: flex;
  height: 80vh;
  max-height: 800px;
  min-height: 500px;
  background: var(--bg-surface);
  border-radius: 24px;
  overflow: hidden;
  box-shadow: 0 24px 80px rgba(124, 58, 237, 0.15), 0 8px 24px rgba(236, 72, 153, 0.08);
  border: 2px solid var(--primary-100);
}

.detail-left {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-root);
  position: relative;
  overflow: hidden;
  padding: var(--space-5);
}

.video-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.detail-video, .detail-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.detail-right {
  width: 280px;
  flex: none;
  background: var(--bg-surface);
  padding: var(--space-5);
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
  overflow-y: auto;
  border-left: 1px solid var(--border-default);
}

/* 竖版视频（9:16）特殊布局 */
.vertical-content {
  height: 85vh;
  max-height: 900px;
}

.vertical-left {
  flex: none;
  width: 45%;
  min-width: 300px;
}

.vertical-container {
  height: 100%;
}

.vertical-content .detail-right {
  flex: 1;
  width: auto;
}

.detail-header {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-full);
  overflow: hidden;
  border: 2px solid var(--border-default);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.username {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-primary);
}

.detail-title-row {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.detail-title-row h3 {
  margin: 0;
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

.category-badge {
  padding: 4px 10px;
  background: var(--gradient-brand);
  border-radius: 20px;
  font-size: 11px;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.2);
}

.description-section {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.section-label {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
}

.description-text {
  font-size: var(--text-xs);
  line-height: var(--leading-relaxed);
  color: var(--text-secondary);
  margin: 0;
}

.copy-icon {
  margin-left: var(--space-1);
  cursor: pointer;
  font-size: var(--text-sm);
  color: var(--text-disabled);
  vertical-align: middle;
}

.copy-icon:hover {
  color: var(--primary-500);
}

.metadata-section {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
  margin-top: auto;
}

.metadata-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-1) 0;
}

.metadata-item .label {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
}

.metadata-item .value {
  font-size: var(--text-xs);
  color: var(--text-primary);
}

.action-section {
  padding-top: var(--space-3);
}

.create-similar-btn {
  width: 100%;
  background: var(--gradient-brand);
  color: #fff;
  border: none;
  border-radius: 12px;
  height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--text-sm);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(124, 58, 237, 0.25);
}

.create-similar-btn:hover {
  box-shadow: 0 6px 24px rgba(124, 58, 237, 0.35);
  transform: translateY(-2px);
}

/* 悬浮操作按钮 */
.overlay-actions {
  position: absolute;
  top: var(--space-5);
  right: var(--space-5);
  display: flex;
  gap: var(--space-3);
  z-index: 20;
}

/* 详情弹窗中的生成中状态 */
.video-processing-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 15;
  border-radius: var(--radius-md);
}

.video-processing-overlay .processing-content {
  text-align: center;
  color: var(--text-primary);
}

.video-processing-overlay .processing-icon {
  color: var(--primary-500);
  margin-bottom: var(--space-4);
}

.video-processing-overlay h3 {
  margin: 0 0 var(--space-2) 0;
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
}

.video-processing-overlay p {
  margin: 0 0 var(--space-5) 0;
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}

.video-processing-overlay .progress-bar-container {
  width: 200px;
  height: 4px;
  background: var(--bg-active);
  border-radius: 2px;
  overflow: hidden;
  margin: 0 auto;
}

.video-processing-overlay .progress-bar-animated {
  height: 100%;
  width: 30%;
  background: linear-gradient(90deg, var(--primary-500), var(--primary-400));
  border-radius: 2px;
  animation: progressSlide 1.5s ease-in-out infinite;
}

@keyframes progressSlide {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(400%); }
}

/* 视频加载失败样式 */
.video-error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 15;
  border-radius: var(--radius-md);
}

.video-error-overlay .error-content {
  text-align: center;
  color: var(--text-primary);
}

.video-error-overlay .error-icon {
  color: var(--error-400);
  margin-bottom: var(--space-4);
}

.video-error-overlay h3 {
  margin: 0 0 var(--space-2) 0;
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
}

.video-error-overlay p {
  margin: 0 0 var(--space-5) 0;
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}

.video-error-overlay .error-actions {
  display: flex;
  gap: var(--space-3);
  justify-content: center;
}

/* 生成中预览图样式 */
.processing-preview {
  opacity: 0.5;
  filter: blur(2px);
}

.icon-btn {
  width: 40px;
  height: 40px;
  border-radius: 12px;
  background: var(--bg-surface);
  border: 2px solid var(--primary-200);
  color: var(--primary-600);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.25s ease;
  font-size: var(--text-lg);
  box-shadow: 0 2px 8px rgba(124, 58, 237, 0.1);
}

.icon-btn:hover {
  background: var(--primary-500);
  border-color: var(--primary-500);
  color: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(124, 58, 237, 0.25);
}

/* 回到顶部按钮样式 */
.back-to-top {
  position: fixed;
  bottom: var(--space-10);
  right: var(--space-10);
  width: 48px;
  height: 48px;
  background: var(--gradient-brand);
  border-radius: var(--radius-full);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(124, 58, 237, 0.3);
  transition: all 0.3s ease;
  z-index: var(--z-toast);
}

.back-to-top:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(124, 58, 237, 0.4);
}

.back-to-top:active {
  transform: translateY(-2px);
}

.back-to-top .anticon {
  font-size: var(--text-2xl);
  color: #fff;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity var(--duration-normal) var(--ease-default), transform var(--duration-normal) var(--ease-default);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 优化加载完成提示样式 */
.finished {
  text-align: center;
  color: var(--primary-600);
  margin: var(--space-5) 0;
  font-size: var(--text-sm);
  font-weight: 600;
  padding: var(--space-3);
  background: linear-gradient(135deg, var(--primary-50), rgba(236, 72, 153, 0.05));
  border-radius: 14px;
  border: 2px solid var(--primary-200);
}

/* 瀑布流响应式 */
@media (max-width: 1200px) {
  .works-grid {
    column-count: 4;
  }
}

@media (max-width: 900px) {
  .works-grid {
    column-count: 3;
  }
}

@media (max-width: 768px) {
  .works-grid {
    column-count: 2;
  }
}

@media (max-width: 480px) {
  .works-grid {
    column-count: 1;
  }
}
</style>

<!-- 全局下拉框深色样式（弹出层传送到body需要非scoped样式） -->
<style>
.ant-select-dropdown {
  background-color: var(--bg-surface) !important;
  border: 1px solid var(--border-default) !important;
}

.ant-select-item {
  color: var(--text-secondary) !important;
}

.ant-select-item:hover,
.ant-select-item.hover {
  background-color: var(--bg-hover) !important;
}

.ant-select-item.is-selected {
  color: var(--primary-500) !important;
  background-color: var(--primary-glow-subtle) !important;
}

.ant-select-dropdown.is-light {
  background-color: var(--bg-surface) !important;
  border: 1px solid var(--border-default) !important;
}

.ant-select-dropdown.is-light .ant-select-dropdown__arrow::before {
  background-color: var(--bg-surface) !important;
  border-color: var(--border-default) !important;
}

/* Sora2.0 SVG 风格标签 */
.badge-pro, .badge-max {
  font-size: 9px;
  padding: 0 3px;
  border-radius: 2px;
  font-weight: var(--font-medium);
  margin-left: var(--space-1);
  background: var(--primary-glow-medium);
  color: var(--primary-400);
  flex: 0 0 auto !important;
  width: auto !important;
}

.badge-max {
  background: rgba(255, 100, 150, 0.2);
  color: #FF7EB3;
}
</style>

<!-- 非 scoped 样式用于 @keyframes 动画 -->
<style>
@keyframes progress-move {
  0% {
    transform: translateX(-100%);
  }
  50% {
    transform: translateX(233%);
  }
  100% {
    transform: translateX(-100%);
  }
}

@keyframes progress-gradient {
  0% {
    background-position: 0% 50%;
  }
  100% {
    background-position: 200% 50%;
  }
}
</style>

<!-- 瀑布流核心样式（非 scoped，确保覆盖 Ant Design CSS-in-JS） -->
<style>
.works-page .works-grid {
  column-count: 5 !important;
  column-gap: var(--space-4) !important;
  display: block !important;
}

.works-page .works-grid-item {
  break-inside: avoid !important;
  margin-bottom: var(--space-4) !important;
  display: inline-block !important;
  width: 100% !important;
}

.works-page .works-grid-item .ant-card {
  width: 100% !important;
}

.works-page .thumb {
  padding-top: 0 !important;
  aspect-ratio: unset !important;
  height: auto !important;
}

.works-page .thumb img {
  position: relative !important;
  width: 100% !important;
  height: auto !important;
  display: block !important;
}

.works-page .work-thumbnail-video {
  position: relative !important;
  width: 100% !important;
  height: auto !important;
  display: block !important;
}

@media (max-width: 1200px) {
  .works-page .works-grid { column-count: 4 !important; }
}
@media (max-width: 900px) {
  .works-page .works-grid { column-count: 3 !important; }
}
@media (max-width: 768px) {
  .works-page .works-grid { column-count: 2 !important; }
}
@media (max-width: 480px) {
  .works-page .works-grid { column-count: 1 !important; }
}
</style>
