<template>
  <div class="image-to-video-page">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <div class="logo">
        <img src="/images/backgrounds/logo.svg?v=2" alt="Logo" />
      </div>
      <nav class="nav-menu">
        <div class="nav-item" @click="goToProfile">
          <UserOutlined />
          <span>个人主页</span>
        </div>
        <div class="nav-item" @click="goToSubscription">
          <CompassOutlined />
          <span>会员订阅</span>
        </div>
        <div class="nav-item" @click="goToMyWorks">
          <FileOutlined />
          <span>我的作品</span>
        </div>
        <div class="nav-divider"></div>
        <div class="nav-item" @click="goToTextToVideo">
          <PlayCircleOutlined />
          <span>文生视频</span>
        </div>
        <div class="nav-item active">
          <PictureOutlined />
          <span>图生视频</span>
        </div>
        <div class="nav-item storyboard-item" @click="goToStoryboardVideo">
          <VideoCameraOutlined />
          <span>分镜视频</span>
        </div>
      </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部用户信息卡片 -->
      <div class="user-info-card">
        <div class="user-avatar">
          <img src="/images/backgrounds/avatar-default.svg" :alt="$t('dashboard.userAvatar')" class="avatar-image" />
        </div>
        <div class="user-details">
          <div class="username">mingzi_FBx7foZYDS7inLQb</div>
          <div class="profile-prompt">还没有设置个人简介,点击填写</div>
          <div class="user-id">ID 2994509784706419</div>
        </div>
        <div class="edit-profile-btn">
          <a-button type="primary">编辑资料</a-button>
        </div>
      </div>

      <!-- 已发布作品区域 -->
      <div class="published-works">
        <div class="works-tabs">
          <div class="tab active">已发布</div>
        </div>
        
        <div class="works-grid">
          <div class="work-item" v-for="(work, index) in publishedWorks" :key="work.taskId || work.id" @click="openDetail(work)">
            <div class="work-thumbnail">
              <!-- 优先使用首帧作为封面，如果没有则使用视频 -->
              <img 
                v-if="work.firstFrameUrl" 
                v-lazy:loading="work.firstFrameUrl"
                :alt="work.title || work.prompt"
                class="work-image-thumbnail"
              />
              <video 
                v-else-if="work.resultUrl" 
                :src="work.resultUrl" 
                class="work-video-thumbnail"
                preload="metadata"
                muted
                @mouseenter="playPreview($event)"
                @mouseleave="pausePreview($event)"
              ></video>
              <!-- 如果都没有，显示占位符 -->
              <div v-else class="work-placeholder">
                <div class="play-icon">▶</div>
              </div>
              <!-- 鼠标悬停时显示的做同款按钮 -->
              <div class="hover-create-btn" @click.stop="goToCreate(work)">
                <a-button type="primary" size="small" round>
                  <PlayCircleOutlined />
                  {{ $t('works.createSimilar') }}
                </a-button>
              </div>
            </div>
            <div class="work-info">
              <div class="work-title">{{ work.prompt || work.title || $t('common.imageToVideoCategory') }}</div>
              <div class="work-meta">{{ work.date || $t('common.unknownDate') }} · {{ work.taskId || work.id }} · {{ formatSize(work) }}</div>
            </div>
            <div class="work-actions" v-if="index === 0">
              <a-button type="primary" class="create-similar-btn" @click.stop="goToCreate(work)">{{ $t('works.createSimilar') }}</a-button>
            </div>
            <div class="work-director" v-else>
              <span>DIRECTED BY VANNOCENT</span>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 作品详情模态框 -->
    <a-modal
      v-model:open="detailDialogVisible"
      :title="selectedItem?.title"
      width="60%"
      class="detail-dialog"
      :modal="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      @close="handleClose"
    >
      <div class="detail-content">
        <div class="detail-left">
          <div class="video-player">
            <img :src="selectedItem?.cover" :alt="selectedItem?.title" class="video-thumbnail" />
            <div class="play-overlay">
              <div class="play-button">▶</div>
            </div>
          </div>
        </div>
        
        <div class="detail-right">
          <div class="metadata-section">
            <div class="metadata-item">
              <span class="label">作品 ID</span>
              <span class="value">{{ selectedItem?.id }}</span>
            </div>
            <div class="metadata-item">
              <span class="label">文件大小</span>
              <span class="value">{{ selectedItem?.size }}</span>
            </div>
            <div class="metadata-item">
              <span class="label">创建时间</span>
              <span class="value">{{ selectedItem?.createTime }}</span>
            </div>
            <div class="metadata-item">
              <span class="label">分类</span>
              <span class="value">{{ selectedItem?.category }}</span>
            </div>
          </div>
          
          <div class="description-section">
            <h3 class="section-title">描述</h3>
            <p class="description-text">{{ getDescription(selectedItem) }}</p>
          </div>
          
          <!-- 操作按钮 -->
          <div class="action-section">
            <button class="create-similar-btn" @click="createSimilar">
              做同款
            </button>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, FileOutlined, PlayCircleOutlined, PictureOutlined, VideoCameraOutlined, CompassOutlined } from '@ant-design/icons-vue'
import { imageToVideoApi } from '@/api/imageToVideo'
import { useI18n } from 'vue-i18n'

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

// 模态框状态
const detailDialogVisible = ref(false)
const selectedItem = ref(null)

// 已发布作品数据
const publishedWorks = ref([])

// 导航函数
const goToProfile = () => {
  router.push('/profile')
}

const goToSubscription = () => {
  router.push('/subscription')
}

const goToMyWorks = () => {
  router.push('/works')
}

const goToTextToVideo = () => {
  router.push('/text-to-video/create')
}

const goToStoryboardVideo = () => {
  router.push('/storyboard-video/create')
}

const goToCreate = (work) => {
  // 跳转到图生视频创作页面
  router.push('/image-to-video/create')
}

// 模态框相关函数
const openDetail = (work) => {
  selectedItem.value = work
  detailDialogVisible.value = true
}

const handleClose = () => {
  detailDialogVisible.value = false
  selectedItem.value = null
}

const getDescription = (item) => {
  if (!item) return ''
  return `这是一个${item.category}作品，展现了"What Does it Mean To You"的主题。作品通过AI技术生成，具有独特的视觉风格和创意表达。`
}

const createSimilar = () => {
  // 关闭模态框并跳转到创作页面
  handleClose()
  router.push('/image-to-video/create')
}

// 格式化文件大小
const formatSize = (work) => {
  if (work.size) return work.size
  return '未知大小'
}

// 播放预览（鼠标悬停时）
const playPreview = (event) => {
  const video = event.target
  if (video && video.tagName === 'VIDEO') {
    video.currentTime = 0
    video.play().catch(() => {
      // 忽略自动播放失败
    })
  }
}

// 暂停预览（鼠标离开时）
const pausePreview = (event) => {
  const video = event.target
  if (video && video.tagName === 'VIDEO') {
    video.pause()
    video.currentTime = 0
  }
}

// 加载任务列表
const loadTasks = async () => {
  try {
    const response = await imageToVideoApi.getTasks(0, 20)
    if (response.data && response.data.success && response.data.data) {
      // 只显示已完成的任务
      publishedWorks.value = response.data.data
        .filter(task => task.status === 'COMPLETED' && (task.resultUrl || task.firstFrameUrl))
        .map(task => ({
          taskId: task.taskId,
          prompt: task.prompt,
          resultUrl: task.resultUrl,
          firstFrameUrl: task.firstFrameUrl,
          status: task.status,
          createdAt: task.createdAt,
          id: task.taskId,
          title: task.prompt || t('common.imageToVideoCategory'),
          text: task.prompt || t('common.imageToVideoCategory'),
          category: t('common.imageToVideoCategory'),
          createTime: task.createdAt ? new Date(task.createdAt).toLocaleString('zh-CN') : '',
          date: task.createdAt ? new Date(task.createdAt).toLocaleDateString('zh-CN') : t('common.unknownDate')
        }))
    }
  } catch (error) {
    console.error('加载任务列表失败:', error)
    message.error(t('common.loadTaskListFailed'))
  }
}

onMounted(() => {
  // 页面初始化时加载任务列表
  loadTasks()
})
</script>

<style scoped>
/* Lazy loading */
.lazy-LoadingOutlined {
  background: linear-gradient(90deg, var(--bg-surface) 25%, var(--bg-elevated) 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; }
}

/* Page layout */
.image-to-video-page {
  display: flex;
  height: 100vh;
  background: var(--bg-base);
  color: var(--text-primary);
  font-family: var(--font-sans);
}

/* Sidebar */
.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: 100 !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 { padding: 0 var(--space-5); }

.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);
  color: var(--text-secondary);
}
.nav-item:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}
.nav-item.active {
  background: var(--primary-glow-light);
  color: var(--primary-400);
}
.nav-item .anticon {
  margin-right: var(--space-3);
  font-size: 18px;
}
.nav-item span {
  font-size: var(--text-sm);
  flex: 1;
}

.nav-divider {
  height: 1px;
  background: var(--border-subtle);
  margin: var(--space-4) 0;
}

/* Main content */
.main-content {
  flex: 1;
  padding: var(--space-5);
  display: flex;
  flex-direction: column;
  gap: var(--space-5);
  overflow-y: auto;
}

/* User info card */
.user-info-card {
  background: var(--bg-surface);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-xl);
  padding: var(--space-6);
  display: flex;
  align-items: center;
  gap: var(--space-5);
}

.user-avatar {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid var(--border-default);
}
.avatar-image { width: 100%; height: 100%; object-fit: cover; }

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}
.username {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}
.profile-prompt {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}
.user-id {
  font-size: var(--text-xs);
  color: var(--text-muted);
}

.edit-profile-btn { margin-left: auto; }

/* Published works */
.published-works {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}
.works-tabs {
  display: flex;
  gap: var(--space-6);
}
.tab {
  padding: var(--space-2) 0;
  color: var(--text-tertiary);
  cursor: pointer;
  position: relative;
  font-size: var(--text-sm);
  transition: var(--transition-colors);
}
.tab.active { color: var(--text-primary); }
.tab.active::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  right: 0;
  height: 2px;
  background: var(--primary-500);
  border-radius: var(--radius-full);
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: var(--space-4);
}

.work-item {
  background: var(--bg-surface);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
  overflow: hidden;
  transition: var(--transition-all);
  cursor: pointer;
}
.work-item:hover {
  border-color: var(--primary-500);
  transform: translateY(-2px);
  box-shadow: var(--glow-primary);
}

.work-thumbnail {
  position: relative;
  aspect-ratio: 16/9;
  overflow: hidden;
}
.work-thumbnail img,
.work-thumbnail video { width: 100%; height: 100%; object-fit: cover; }
.work-image-thumbnail,
.work-video-thumbnail { display: block; background: #000; }
.work-placeholder {
  width: 100%; height: 100%;
  background: var(--bg-base);
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-icon {
  width: 56px; height: 56px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-primary);
  font-size: 22px;
}

/* Hover create button */
.hover-create-btn {
  position: absolute;
  right: var(--space-2);
  bottom: var(--space-2);
  opacity: 0;
  transform: translateY(8px);
  transition: var(--transition-all);
  z-index: 10;
}
.work-thumbnail:hover .hover-create-btn {
  opacity: 1;
  transform: translateY(0);
}
.hover-create-btn .ant-btn {
  background: var(--primary-500);
  border: none;
  backdrop-filter: blur(8px);
  box-shadow: var(--glow-primary);
}

.work-info {
  padding: var(--space-3);
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}
.work-title {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.work-meta {
  font-size: var(--text-xs);
  color: var(--text-muted);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.work-actions {
  padding: 0 var(--space-3) var(--space-3);
  opacity: 0;
  transition: var(--transition-base);
}
.work-item:hover .work-actions { opacity: 1; }

.work-director {
  padding: 0 var(--space-3) var(--space-3);
  text-align: center;
}
.work-director span {
  font-size: var(--text-xs);
  color: var(--text-muted);
  font-style: italic;
}

/* Responsive */
@media (max-width: 768px) {
  .image-to-video-page { flex-direction: column; }
  .sidebar { width: 100% !important; height: auto !important; }
  .works-grid { grid-template-columns: 1fr; }
}

/* Detail Dialog */
:deep(.detail-dialog .ant-modal) {
  background: var(--bg-base) !important;
  border-radius: var(--radius-xl);
  border: 1px solid var(--border-default) !important;
  box-shadow: var(--shadow-xl);
}
:deep(.detail-dialog .ant-modal-header),
:deep(.ant-modal-header) {
  background: transparent !important;
  border-bottom: 1px solid var(--border-subtle);
}
:deep(.detail-dialog .ant-modal-title),
:deep(.ant-modal-title) {
  color: var(--text-primary) !important;
}
:deep(.detail-dialog .ant-modal-close),
:deep(.ant-modal-close) {
  color: var(--text-secondary) !important;
}
:deep(.detail-dialog .ant-modal-body),
:deep(.ant-modal-body) {
  background: transparent !important;
  padding: 0 !important;
}
:deep(.ant-modal-wrap),
:deep(.ant-modal-mask) {
  background-color: rgba(0, 0, 0, 0.75) !important;
}

.detail-content {
  display: flex;
  height: 50vh;
  background: var(--bg-base);
}
.detail-left {
  flex: 1;
  padding: var(--space-5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.video-player {
  position: relative;
  width: 100%;
  max-width: 400px;
  aspect-ratio: 16/9;
  border-radius: var(--radius-lg);
  overflow: hidden;
  cursor: pointer;
}
.video-thumbnail { width: 100%; height: 100%; object-fit: cover; }
.play-overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: var(--transition-base);
}
.video-player:hover .play-overlay { opacity: 1; }
.play-button {
  width: 56px; height: 56px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  color: #000;
}

.detail-right {
  flex: 1;
  padding: var(--space-5);
  background: var(--bg-base);
  display: flex;
  flex-direction: column;
  gap: var(--space-5);
}
.metadata-section {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}
.metadata-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-2) 0;
  border-bottom: 1px solid var(--border-subtle);
}
.metadata-item:last-child { border-bottom: none; }
.label { font-size: var(--text-sm); color: var(--text-tertiary); }
.value { font-size: var(--text-sm); color: var(--text-primary); font-weight: var(--font-medium); }

.description-section { flex: 1; }
.section-title {
  font-size: var(--text-base);
  color: var(--text-primary);
  font-weight: var(--font-semibold);
  margin-bottom: var(--space-3);
}
.description-text {
  font-size: var(--text-sm);
  color: var(--text-secondary);
  line-height: var(--leading-relaxed);
  margin: 0;
}
.action-section { margin-top: auto; }
.create-similar-btn {
  width: 100%;
  background: var(--primary-500);
  color: var(--text-inverse);
  border: none;
  padding: var(--space-3) var(--space-6);
  border-radius: var(--radius-md);
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  cursor: pointer;
  transition: var(--transition-all);
}
.create-similar-btn:hover {
  background: var(--primary-400);
  box-shadow: var(--glow-primary);
  transform: translateY(-1px);
}
</style>
