<template>
  <div class="work-detail-page" @contextmenu.prevent="handleContextMenu" @wheel.prevent="handleWheelSwitch">
    <button class="back-button" @click="handleBack" title="返回">
      X
    </button>
    <!-- 加载状态 -->
    <div v-if="!workData && loading" class="loading-container">
      <div class="spinner"></div>
      <p>正在加载作品...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>加载作品失败：{{ error }}</p>
      <button @click="onMounted">重试</button>
    </div>

    <!-- 内容展示 -->
    <div v-else-if="workData" class="detail-layout">
      <!-- 左侧媒体展示 -->
      <div class="media-container">
        <div 
          v-if="workData.resultUrl && !isImage(workData.resultUrl)"
          class="custom-player-container"
          ref="playerContainerRef"
          @mouseenter="isHoveringControls = true"
          @mouseleave="isHoveringControls = false"
          @contextmenu.prevent
        >
          <video 
            :src="workData.resultUrl" 
            autoplay 
            loop 
            playsinline 
            ref="mainVideoPlayer"
            @timeupdate="updateProgress"
            @loadedmetadata="initPlayer"
            @play="isPlaying = true"
            @pause="isPlaying = false"
            @volumechange="onVolumeChange"
            @click.prevent="togglePlay"
          ></video>
          <div class="controls-overlay" :class="{ visible: isHoveringControls || !isPlaying }">
            <div class="progress-bar-wrapper" @click="handleScrub">
              <div class="progress-bar-filled" :style="{ width: progress + '%' }"></div>
            </div>
            <div class="controls-left">
              <button @click.stop="togglePlay" class="control-btn">
                <svg v-if="!isPlaying" viewBox="0 0 24 24"><path fill="currentColor" d="M8 5v14l11-7z"></path></svg>
                <svg v-else viewBox="0 0 24 24"><path fill="currentColor" d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></svg>
              </button>
              <div class="volume-container">
                <button @click.stop="toggleMute" class="control-btn">
                  <svg v-if="!isMuted && volume > 0.5" viewBox="0 0 24 24"><path fill="currentColor" d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"></path></svg>
                  <svg v-else-if="!isMuted && volume > 0" viewBox="0 0 24 24"><path fill="currentColor" d="M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z"></path></svg>
                  <svg v-else viewBox="0 0 24 24"><path fill="currentColor" d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"></path></svg>
                </button>
                <input type="range" min="0" max="1" step="0.01" :value="volume" @input="setVolume" class="volume-slider" />
              </div>
              <span class="time-display">{{ formattedCurrentTime }} / {{ formattedDuration }}</span>
            </div>
            <div class="controls-right">
               <button @click.stop="toggleFullscreen" class="control-btn">
                <svg viewBox="0 0 24 24"><path fill="currentColor" d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"></path></svg>
              </button>
            </div>
          </div>
        </div>
        <img v-else-if="workData.resultUrl && isImage(workData.resultUrl)" :src="workData.resultUrl" alt="作品图片" class="work-image" />
        <div v-else class="media-placeholder">媒体资源不可用</div>
      </div>

      <!-- 右侧信息 -->
      <div class="info-container">
        <div class="info-content">
          <!-- 作者信息 -->
          <div class="author-info">
            <img :src="workData.author?.avatarUrl" alt="作者头像" class="author-avatar" />
            <div class="author-details">
              <span class="author-nickname">{{ workData.author?.nickname || '匿名用户' }}</span>
              <span class="create-time">{{ formatTime(workData.createTime) }} | 内容由AI生成</span>
            </div>
          </div>

          <!-- Prompt 信息 -->
          <div class="prompt-section" v-if="workData.prompt">
            <div class="prompt-header">
              <h2>Prompt</h2>
              <div class="prompt-actions">
                <button @click="copyPrompt" class="prompt-action-btn">
                  复制
                </button>
                <button @click="showFullPrompt = !showFullPrompt" class="prompt-action-btn">
                  {{ showFullPrompt ? '收起' : '显示全部' }}
                </button>
              </div>
            </div>
            <div class="prompt-content">
              <pre>{{ formattedPrompt }}</pre>
            </div>
          </div>
       
          <!-- 标签 -->
          <div v-if="workData.tags && workData.tags.length > 0" class="tags-container">
            <span v-for="tag in workData.tags" :key="tag" class="tag">#{{ tag }}</span>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="actions-bar">
          <button class="action-btn make-same" @click="handleMakeSame">
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.61101 9.6016L5.62614 9.58705C6.40213 8.84062 7.63279 8.85257 8.39415 9.61392L8.4322 9.65197C9.19354 10.4133 9.18187 11.6512 8.40632 12.3981M2.51103 15.4968C1.73591 14.7217 1.73591 13.465 2.51103 12.6898L8.18934 7.01152C8.96447 6.23639 10.2212 6.2364 10.9963 7.01152C11.7714 7.78664 11.7714 9.04336 10.9963 9.81848L5.318 15.4968C4.54287 16.2719 3.28615 16.2719 2.51103 15.4968Z" stroke="currentColor" stroke-width="1.125" stroke-linecap="round"/><path d="M12.9373 1.5207C13.1306 0.998333 13.8694 0.998333 14.0627 1.5207L14.4171 2.47841C14.4779 2.64265 14.6074 2.77213 14.7716 2.8329L15.7293 3.18729C16.2517 3.38058 16.2517 4.11942 15.7293 4.31271L14.7716 4.6671C14.6074 4.72787 14.4779 4.85735 14.4171 5.02159L14.0627 5.9793C13.8694 6.50167 13.1306 6.50167 12.9373 5.9793L12.5829 5.02159C12.5221 4.85735 12.3926 4.72787 12.2284 4.6671L11.2707 4.31271C10.7483 4.11942 10.7483 3.38058 11.2707 3.18729L12.2284 2.8329C12.3926 2.77213 12.5221 2.64265 12.5829 2.47841L12.9373 1.5207Z" fill="currentColor"/><path d="M14.6483 7.70044C14.7691 7.37396 15.2309 7.37396 15.3517 7.70044L15.7504 8.77801C15.7884 8.88066 15.8693 8.96159 15.972 8.99957L17.0496 9.39831C17.376 9.51911 17.376 9.98089 17.0496 10.1017L15.972 10.5004C15.8693 10.5384 15.7884 10.6193 15.7504 10.722L15.3517 11.7996C15.2309 12.126 14.7691 12.126 14.6483 11.7996L14.2496 10.722C14.2116 10.6193 14.1307 10.5384 14.028 10.5004L12.9504 10.1017C12.624 9.98089 12.624 9.51911 12.9504 9.39831L14.028 8.99957C14.1307 8.96159 14.2116 8.88066 14.2496 8.77801L14.6483 7.70044Z" fill="currentColor"/></svg>
              做同款
          </button>
          <div class="stats">
            <span class="stat-item">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.6416 2.70624C9.74244 2.40684 10.2576 2.40684 10.3584 2.70624C10.77 3.9652 11.5418 5.8004 12.833 7.0916C14.091 8.35057 15.9396 9.11161 17.203 9.47361C17.5079 9.5777 17.5039 10.0127 17.1983 10.1135C16.0919 10.493 14.3744 11.2418 13.0832 12.533C11.7744 13.8418 11.0189 15.6748 10.6433 16.9375C10.5451 17.2346 10.0465 17.2443 9.9409 16.9442C9.52144 15.6621 8.7381 14.005 7.50013 12.833C6.23767 11.6365 4.31242 10.9216 2.90285 10.5703C2.59627 10.4854 2.59936 10.0459 2.90563 9.96704C3.99727 9.61528 5.86021 8.87528 7.0916 7.0916C8.3075 5.8004 9.07947 3.9652 9.6416 2.70624Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/></svg>
              {{ workData.viewCount || 0 }}
            </span>
            <span class="stat-item clickable" @click="toggleLike">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.25081 3.33301C3.71951 3.33301 1.66748 5.38504 1.66748 7.91634C1.66748 12.4997 7.08415 16.6663 10.0008 17.6358C12.9175 16.6663 18.3341 12.4997 18.3341 7.91634C18.3341 5.38504 16.2821 3.33301 13.7508 3.33301C12.2007 3.33301 10.8303 4.10267 10.0008 5.28055C9.17131 4.10267 7.801 3.33301 6.25081 3.33301Z" :fill="workData.isLiked ? 'currentColor' : 'none'" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/></svg>
              {{ workData.likeCount || 0 }}
            </span>
            <span class="stat-item clickable" @click="sharePage">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M18 8C18 9.10457 17.1046 10 16 10C14.8954 10 14 9.10457 14 8C14 6.89543 14.8954 6 16 6C17.1046 6 18 6.89543 18 8ZM6 12C6 13.1046 5.10457 14 4 14C2.89543 14 2 13.1046 2 12C2 10.8954 2.89543 10 4 10C5.10457 10 6 10.8954 6 12ZM18 16C18 17.1046 17.1046 18 16 18C14.8954 18 14 17.1046 14 16C14 14.8954 14.8954 14 16 14C17.1046 14 18 14.8954 18 16ZM6.05025 10.5L13.9497 7.5M13.9497 16.5L6.05025 13.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </span>
          </div>
        </div>
      </div>

      <!-- 右侧视频流 -->
      <div class="work-carousel-container" @wheel.prevent="handleWheelSwitch">
        <!-- Skeleton Loader -->
        <div v-if="carouselLoading && carouselWorks.length === 0" class="carousel-list">
          <div v-for="n in 5" :key="n" class="carousel-item-skeleton"></div>
        </div>
        <!-- Real Content -->
        <div v-else-if="carouselWorks.length > 0" class="carousel-list" ref="carouselListRef" :style="{ transform: `translateY(${activeWorkTranslateY}px)` }">
          <router-link
            v-for="work in carouselWorks"
            :key="work.uid"
            :to="{ name: 'AIApplicationWorkDetail', params: { id: work.workNo || work.uid } }"
            class="carousel-item"
            :class="{ active: workData && work.uid === workData.uid }"
          >
            <video
              v-if="work.resultUrl && !isImage(work.resultUrl)"
              :src="work.resultUrl + '#t=0.5'"
              class="carousel-thumbnail"
              preload="metadata"
              muted
              playsinline
            ></video>
            <img
              v-else-if="work.resultUrl && isImage(work.resultUrl)"
              :src="work.resultUrl"
              :alt="work.title"
              class="carousel-thumbnail"
              loading="lazy"
            />
            <div v-else class="thumbnail-placeholder"></div>
            <!-- Title overlay removed for a cleaner look -->
          </router-link>
          <div v-if="carouselLoading" class="carousel-loading">
            <div class="spinner-small"></div>
          </div>
        </div>
        <div v-else-if="!carouselLoading" class="carousel-empty">
          <p>没有更多作品了</p>
        </div>
      </div>
    </div>

    <!-- 自定义右键菜单 -->
    <div v-if="contextMenu.visible" class="context-menu" :style="{ top: `${contextMenu.y}px`, left: `${contextMenu.x}px` }">
      <button class="context-menu-item" @click="toggleLike">
        <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.25081 3.33301C3.71951 3.33301 1.66748 5.38504 1.66748 7.91634C1.66748 12.4997 7.08415 16.6663 10.0008 17.6358C12.9175 16.6663 18.3341 12.4997 18.3341 7.91634C18.3341 5.38504 16.2821 3.33301 13.7508 3.33301C12.2007 3.33301 10.8303 4.10267 10.0008 5.28055C9.17131 4.10267 7.801 3.33301 6.25081 3.33301Z" :fill="workData.isLiked ? 'currentColor' : 'none'" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/></svg>
        <span>{{ workData.isLiked ? '取消点赞' : '点赞' }}</span>
      </button>
      <button class="context-menu-item" @click="handleMakeSame">
        <svg viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.61101 9.6016L5.62614 9.58705C6.40213 8.84062 7.63279 8.85257 8.39415 9.61392L8.4322 9.65197C9.19354 10.4133 9.18187 11.6512 8.40632 12.3981M2.51103 15.4968C1.73591 14.7217 1.73591 13.465 2.51103 12.6898L8.18934 7.01152C8.96447 6.23639 10.2212 6.2364 10.9963 7.01152C11.7714 7.78664 11.7714 9.04336 10.9963 9.81848L5.318 15.4968C4.54287 16.2719 3.28615 16.2719 2.51103 15.4968Z" stroke="currentColor" stroke-width="1.125" stroke-linecap="round"/><path d="M12.9373 1.5207C13.1306 0.998333 13.8694 0.998333 14.0627 1.5207L14.4171 2.47841C14.4779 2.64265 14.6074 2.77213 14.7716 2.8329L15.7293 3.18729C16.2517 3.38058 16.2517 4.11942 15.7293 4.31271L14.7716 4.6671C14.6074 4.72787 14.4779 4.85735 14.4171 5.02159L14.0627 5.9793C13.8694 6.50167 13.1306 6.50167 12.9373 5.9793L12.5829 5.02159C12.5221 4.85735 12.3926 4.72787 12.2284 4.6671L11.2707 4.31271C10.7483 4.11942 10.7483 3.38058 11.2707 3.18729L12.2284 2.8329C12.3926 2.77213 12.5221 2.64265 12.5829 2.47841L12.9373 1.5207Z" fill="currentColor"/><path d="M14.6483 7.70044C14.7691 7.37396 15.2309 7.37396 15.3517 7.70044L15.7504 8.77801C15.7884 8.88066 15.8693 8.96159 15.972 8.99957L17.0496 9.39831C17.376 9.51911 17.376 9.98089 17.0496 10.1017L15.972 10.5004C15.8693 10.5384 15.7884 10.6193 15.7504 10.722L15.3517 11.7996C15.2309 12.126 14.7691 12.126 14.6483 11.7996L14.2496 10.722C14.2116 10.6193 14.1307 10.5384 14.028 10.5004L12.9504 10.1017C12.624 9.98089 12.624 9.51911 12.9504 9.39831L14.028 8.99957C14.1307 8.96159 14.2116 8.88066 14.2496 8.77801L14.6483 7.70044Z" fill="currentColor"/></svg>
        <span>做同款</span>
      </button>
      <button class="context-menu-item" @click="sharePage">
        <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
          <!-- Share Icon Placeholder -->
          <path d="M18 8C18 9.10457 17.1046 10 16 10C14.8954 10 14 9.10457 14 8C14 6.89543 14.8954 6 16 6C17.1046 6 18 6.89543 18 8ZM6 12C6 13.1046 5.10457 14 4 14C2.89543 14 2 13.1046 2 12C2 10.8954 2.89543 10 4 10C5.10457 10 6 10.8954 6 12ZM18 16C18 17.1046 17.1046 18 16 18C14.8954 18 14 17.1046 14 16C14 14.8954 14.8954 14 16 14C17.1046 14 18 14.8954 18 16ZM6.05025 10.5L13.9497 7.5M13.9497 16.5L6.05025 13.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <span>分享</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getWorkDetail, likeWork, unlikeWork, getPlazaWorks } from '@/api'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const workData = ref(null)
const loading = ref(true)
const error = ref(null)
const showFullPrompt = ref(false)
const entryRoute = ref(null)

// 视频流数据
const carouselWorks = ref([])
const carouselPage = ref(1)
const carouselLoading = ref(false)
const carouselHasMore = ref(true)
const carouselListRef = ref(null)
const wheelTimeout = ref(null)
const activeWorkTranslateY = ref(0)
const mainVideoPlayer = ref(null)

// --- Back Button Logic ---
const handleBack = () => {
  if (entryRoute.value) {
    router.push(entryRoute.value);
  } else {
    // If no entry route (direct link or history is not clear), go to homepage
    router.push('/');
  }
};

// Player State
const playerContainerRef = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const volume = ref(1)
const isMuted = ref(false)
const isHoveringControls = ref(false)

// Computed properties for display
const progress = computed(() => (duration.value > 0 ? (currentTime.value / duration.value) * 100 : 0))
const formattedCurrentTime = computed(() => formatVideoTime(currentTime.value))
const formattedDuration = computed(() => formatVideoTime(duration.value))

// --- Data Adapter ---
const normalizeWork = (work) => {
  if (!work) return null;
  // Keep all original properties and add a reliable internal UID
  return {
    ...work,
    uid: work.workNo || work.taskNo,
  };
};

const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
})

// 格式化Prompt，处理JSON字符串
const formattedPrompt = computed(() => {
  if (!workData.value?.prompt) return '暂无Prompt'
  try {
    const parsed = JSON.parse(workData.value.prompt)
    // 美化JSON输出
    const prettyJson = JSON.stringify(parsed, null, 2)
    if (!showFullPrompt.value && prettyJson.length > 200) {
      return prettyJson.substring(0, 200) + '...'
    }
    return prettyJson
  } catch (e) {
    // 如果不是JSON，直接返回原始字符串
    const promptText = workData.value.prompt
    if (!showFullPrompt.value && promptText.length > 200) {
      return promptText.substring(0, 200) + '...'
    }
    return promptText
  }
})

// 处理右键菜单
const handleContextMenu = (event) => {
  event.preventDefault()
  contextMenu.value.visible = true
  contextMenu.value.x = event.clientX
  contextMenu.value.y = event.clientY

  // Add a click listener to close the menu
  window.addEventListener('click', closeContextMenu, { once: true })
}

const closeContextMenu = () => {
  contextMenu.value.visible = false
}

// 复制Prompt
const copyPrompt = async () => {
  if (!workData.value?.prompt) {
    ElMessage.warning('没有可复制的Prompt')
    return
  }

  try {
    await navigator.clipboard.writeText(workData.value.prompt)
    ElMessage.success('Prompt已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 分享页面
const sharePage = async () => {
  try {
    await navigator.clipboard.writeText(window.location.href)
    ElMessage.success('链接已复制，快去分享吧！')
  } catch (err) {
    console.error('复制链接失败:', err)
    ElMessage.error('复制链接失败，请手动复制')
  }
}

// 判断是否为图片URL
const isImage = (url) => {
  if (!url) return false
  return /\.(jpg|jpeg|png|webp|gif)$/i.test(url)
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}

// --- Player Methods ---
function formatVideoTime(seconds) {
  if (isNaN(seconds) || seconds < 0) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

function initPlayer(event) {
  duration.value = event.target.duration
  volume.value = event.target.volume
  isMuted.value = event.target.muted
}

function updateProgress(event) {
  currentTime.value = event.target.currentTime
}

function onVolumeChange(event) {
  volume.value = event.target.volume
  isMuted.value = event.target.muted
}

function togglePlay() {
  if (!mainVideoPlayer.value) return
  if (mainVideoPlayer.value.paused) {
    mainVideoPlayer.value.play()
  } else {
    mainVideoPlayer.value.pause()
  }
}

function handleScrub(event) {
  if (!mainVideoPlayer.value) return
  const progressBar = event.currentTarget
  const rect = progressBar.getBoundingClientRect()
  const clickX = event.clientX - rect.left
  const percentage = clickX / rect.width
  mainVideoPlayer.value.currentTime = duration.value * percentage
}

function toggleMute() {
  if (!mainVideoPlayer.value) return
  mainVideoPlayer.value.muted = !mainVideoPlayer.value.muted
}

function setVolume(event) {
    if (!mainVideoPlayer.value) return
    const newVolume = parseFloat(event.target.value)
    mainVideoPlayer.value.volume = newVolume
    if (newVolume > 0 && mainVideoPlayer.value.muted) {
        mainVideoPlayer.value.muted = false
    }
}

function toggleFullscreen() {
    if (!playerContainerRef.value) return
    if (!document.fullscreenElement) {
        playerContainerRef.value.requestFullscreen().catch(err => {
          console.error(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
        });
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
    }
}


// 获取视频流数据
const fetchCarouselWorks = async () => {
  if (carouselLoading.value || !carouselHasMore.value) return

  carouselLoading.value = true
  try {
    const params = {
      page: carouselPage.value,
      pageSize: 10
    }
    const res = await getPlazaWorks(params)

    if (res.code === 200 && res.data?.list) {
      const works = res.data.list
      const existingUids = new Set(carouselWorks.value.map(w => w.uid))
      
      const uniqueNewWorks = works
        .map(normalizeWork)
        .filter(w => w && !existingUids.has(w.uid));

      if (works.length === 0) {
        carouselHasMore.value = false
      } else {
        carouselWorks.value.push(...uniqueNewWorks)
        carouselPage.value++
      }
    } else {
      carouselHasMore.value = false
    }
  } catch (err) {
    console.error('获取作品列表失败:', err)
  } finally {
    carouselLoading.value = false
  }
}

// 视频流无限滚动
const handleCarouselScroll = (event) => {
  const { scrollTop, clientHeight, scrollHeight } = event.target
  // 滚动到接近底部时加载更多
  if (scrollHeight - scrollTop - clientHeight < 200) {
    fetchCarouselWorks()
  }
}

// 滚轮切换视频
const handleWheelSwitch = (event) => {
  if (wheelTimeout.value || loading.value) return

  const currentUid = workData.value?.uid
  if (!currentUid) return
  
  const currentIndex = carouselWorks.value.findIndex(w => w.uid === currentUid)
  if (currentIndex === -1) return

  let nextIndex = -1
  if (event.deltaY > 0) { // Down
    if (currentIndex < carouselWorks.value.length - 1) {
      nextIndex = currentIndex + 1
    }
  } else { // Up
    if (currentIndex > 0) {
      nextIndex = currentIndex - 1
    }
  }

  if (nextIndex !== -1) {
    // Infinite scroll trigger
    if (event.deltaY > 0 && carouselHasMore.value && !carouselLoading.value && carouselWorks.value.length - nextIndex < 5) {
      fetchCarouselWorks()
    }

    const nextWork = carouselWorks.value[nextIndex]
    router.push({ name: 'AIApplicationWorkDetail', params: { id: nextWork.workNo || nextWork.uid } })
    
    wheelTimeout.value = setTimeout(() => {
      wheelTimeout.value = null
    }, 500) // 500ms throttle to match animation
  }
}

// 滚动到当前激活的视频
const scrollToActiveWork = async () => {
  await nextTick()
  if (!carouselListRef.value || !workData.value) return

  const currentUid = workData.value.uid
  const activeIndex = carouselWorks.value.findIndex(w => w.uid === currentUid)

  if (activeIndex === -1) {
    // Fallback: if not found, scroll to top
    activeWorkTranslateY.value = 0
    return
  }

  const container = carouselListRef.value
  const cardElements = container.children // HTMLCollection of router-links
  const cardElement = cardElements[activeIndex]
  
  if (!cardElement) return

  const containerHeight = container.parentElement.clientHeight
  const cardHeight = cardElement.offsetHeight
  
  const elementOffsetTop = cardElement.offsetTop

  // The target position for the top of the card to be centered in the container.
  const targetPosition = (containerHeight / 2) - (cardHeight / 2)

  const newTranslateY = targetPosition - elementOffsetTop

  activeWorkTranslateY.value = newTranslateY

  // Autoplay the video
  await nextTick()
  if (mainVideoPlayer.value) {
    try {
      await mainVideoPlayer.value.play()
    } catch (error) {
      console.error("Autoplay failed:", error)
    }
  }
}

// 获取作品详情
const fetchWorkDetail = async () => {
  error.value = null
  try {
    const workId = route.params.id
    if (!workId) {
      throw new Error('作品ID无效')
    }
    const res = await getWorkDetail(workId)
    if (res?.code === 200 && res.data) {
      workData.value = normalizeWork(res.data)
    } else {
      throw new Error(res?.message || '无法加载作品数据')
    }
  } catch (err) {
    error.value = err.message
    console.error('获取作品详情失败:', err)
  }
}

// 点赞/取消点赞
const toggleLike = async () => {
  if (!workData.value) return

  const originalLiked = workData.value.isLiked
  const originalCount = workData.value.likeCount

  try {
    // 乐观更新UI
    workData.value.isLiked = !originalLiked
    workData.value.likeCount += originalLiked ? -1 : 1

    if (workData.value.isLiked) {
      await likeWork(workData.value.workNo)
      ElMessage.success('点赞成功')
    } else {
      await unlikeWork(workData.value.workNo)
      ElMessage.success('取消点赞成功')
    }
  } catch (err) {
    // 失败回滚
    workData.value.isLiked = originalLiked
    workData.value.likeCount = originalCount
    ElMessage.error(err.message || '操作失败')
  }
}

// 做同款
const handleMakeSame = () => {
  if (!workData.value) return

  const detailWork = workData.value
  let routePath = ''
  let query = {}

  switch (detailWork.taskType) {
    case 'text_to_video':
      routePath = '/ai-application/create'
      query = {
        mode: 'text',
        prompt: detailWork.prompt,
        aspectRatio: detailWork.aspectRatio,
        modelName: detailWork.modelName
      }
      break
    case 'image_to_video':
      routePath = '/ai-application/create'
      query = {
        mode: 'image',
        prompt: detailWork.prompt,
        imageUrl: detailWork.imageUrl,
        aspectRatio: detailWork.aspectRatio,
        modelName: detailWork.modelName
      }
      break
    case 'text_to_image':
      routePath = '/ai-application/image-create'
      query = {
        prompt: detailWork.prompt,
        imageUrl: detailWork.imageUrl,
        aspectRatio: detailWork.aspectRatio
      }
      break
    case 'storyboard_video':
    case 'storyboard_to_video':
      routePath = '/ai-application/create'
      query = {
        mode: 'storyboard',
        prompt: detailWork.prompt,
        imageUrl: detailWork.imageUrl,
        aspectRatio: detailWork.aspectRatio
      }
      break
    default:
      ElMessage.warning('暂不支持该类型的“做同款”功能')
      return
  }

  router.push({ path: routePath, query })
}


onMounted(async () => {
  // Capture the entry route only when the component is first mounted.
  // This value will persist across same-component navigations (video switching).
  const backRoute = window.history.state.back;
  if (backRoute && !backRoute.startsWith('/ai-application/work/')) {
    entryRoute.value = backRoute;
  }

  loading.value = true
  
  try {
    // 步骤1: 先获取作品详情
    await fetchWorkDetail()
    console.log("先获取详情")
    // 步骤2: 等待作品详情加载完成后，再获取轮播列表
    await fetchCarouselWorks()
console.log("轮播图")
    // 步骤3: 确保当前作品在轮播列表中
    // 处理用户直接导航到不在第一页的作品的情况
    if (workData.value?.uid && !carouselWorks.value.some(w => w.uid === workData.value.uid)) {
      carouselWorks.value.unshift(workData.value);
    }
console.log("确保")
    loading.value = false
    await nextTick()
    
    // 步骤4: 滚动到激活的作品位置
    scrollToActiveWork()
  } catch (err) {
    console.error('页面初始化失败:', err)
    loading.value = false
  }
})

watch(() => route.params.id, async (newId, oldId) => {
  if (newId && newId !== oldId) {
    // Only fetch main work detail, carousel list persists
    await fetchWorkDetail()
    scrollToActiveWork()
  }
})
</script>

<style scoped>
.work-detail-page {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #151515;
  color: #fff;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.back-button {
  position: absolute;
  top: 25px;
  left: 30px;
  z-index: 100;
  background-color: rgba(30, 30, 30, 0.7);
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 50%;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: rgba(50, 50, 50, 0.9);
  transform: scale(1.1);
}

.back-button svg {
  width: 24px;
  height: 24px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  font-size: 1.2rem;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(255, 255, 255, 0.2);
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-container button {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #3b82f6;
  border: none;
  color: white;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.error-container button:hover {
  background-color: #2563eb;
}

.detail-layout {
  position: relative;
  display: flex;
  flex-grow: 1;
  height: 100%;
  overflow: hidden;
}

.media-container {
  flex: 1;
  background-color: #000;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0; /* Remove padding to allow player to fill */
  box-sizing: border-box;
  overflow: hidden; /* Prevent scrollbars from player */
}

.media-wrapper {
  max-width: 100%;
  max-height: 100%;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.work-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 16px;
}

/* --- Custom Player Styles --- */
.custom-player-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-player-container video {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 16px; /* Keep the rounded corners */
}

.controls-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  color: white;
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background: linear-gradient(to top, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
  box-sizing: border-box;
  border-bottom-left-radius: 16px;
  border-bottom-right-radius: 16px;
}

.controls-overlay.visible {
  opacity: 1;
}

.controls-left, .controls-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.controls-right {
  margin-left: auto;
}

.control-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
}

.control-btn svg {
  width: 100%;
  height: 100%;
}

.progress-bar-wrapper {
  position: absolute;
  top: -5px; /* Position it just above the control bar */
  left: 0;
  right: 0;
  height: 10px;
  cursor: pointer;
  padding: 2.5px 0;
  box-sizing: border-box;
}

.progress-bar-wrapper::before {
  content: '';
  position: absolute;
  left: 20px;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  height: 5px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.progress-bar-filled {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  height: 5px;
  background-color: #fff;
  border-radius: 3px;
  max-width: calc(100% - 40px);
}

.time-display {
  font-size: 12px;
  font-family: 'Montserrat', sans-serif;
  min-width: 90px;
}

.volume-container {
  display: flex;
  align-items: center;
}

.volume-slider {
  -webkit-appearance: none;
  appearance: none;
  width: 70px;
  height: 5px;
  background: rgba(255, 255, 255, 0.3);
  outline: none;
  border-radius: 3px;
  transition: opacity 0.2s;
  opacity: 0;
  cursor: pointer;
}

.volume-container:hover .volume-slider {
  opacity: 1;
}

.volume-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 12px;
  height: 12px;
  background: #fff;
  border-radius: 50%;
  cursor: pointer;
}

.volume-slider::-moz-range-thumb {
  width: 12px;
  height: 12px;
  background: #fff;
  border-radius: 50%;
  cursor: pointer;
}


.work-carousel-container {
  width: 100px;
  flex-shrink: 0;
  background-color: #000;
  border-left: 1px solid #2a2a2a;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px 0;
  box-sizing: border-box;
  overflow: hidden;
}

.carousel-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  transition: transform 0.5s cubic-bezier(0.25, 1, 0.5, 1);
}

/* Hide scrollbar for Chrome, Safari and Opera */
.carousel-list::-webkit-scrollbar {
  display: none;
}

/* Hide scrollbar for IE, Edge and Firefox */
.carousel-list {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.carousel-item {
  position: relative;
  display: block;
  width: 67px;
  height: 127px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 3px solid transparent;
  transition: all 0.3s ease;
  box-sizing: border-box;
  margin: 0 auto;
  flex-shrink: 0;
}

.carousel-item.active {
  border-color: #fff;
  transform: scale(1.05);
}

.carousel-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: #222;
}

.thumbnail-placeholder {
  width: 100%;
  height: 100%;
  background-color: #222;
}

.carousel-loading, .carousel-empty {
  padding: 20px;
  text-align: center;
  color: #666;
}

.spinner-small {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(255, 255, 255, 0.2);
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

.carousel-item-skeleton {
  width: 67px;
  height: 127px;
  border-radius: 8px;
  background-color: #2a2a2a;
  animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
  margin: 0 auto;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.context-menu {
  position: fixed;
  z-index: 1000;
  background-color: rgba(30, 30, 30, 0.7);
  backdrop-filter: blur(10px);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.context-menu-item {
  background: none;
  border: none;
  color: #fff;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  text-align: left;
  transition: background-color 0.2s;
}

.context-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.context-menu-item svg {
  width: 16px;
  height: 16px;
}

.media-placeholder {
  color: #666;
  align-self: center;
}

.info-container {
  width: 325px;
  flex-shrink: 0;
  background: #1c1c1c;
  border-left: 1px solid #2a2a2a;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.info-content {
  padding: 30px;
  overflow-y: auto;
  flex-grow: 1;
}

.actions-bar {
  padding: 20px 30px;
  border-top: 1px solid #2a2a2a;
  background-color: #1c1c1c;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 15px;
  border: 2px solid #333;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-nickname {
  color: rgba(255, 255, 255, 1);
  font-family: 'PingFang SC', sans-serif;
  font-size: 12px;
  font-weight: 400;
  line-height: 20px;
  letter-spacing: 0%;
  text-align: left;
}

.create-time {
  font-size: 12px;
  color: #999;
  font-family: 'Montserrat', sans-serif;
}

.work-title {
  font-size: 2rem;
  font-weight: bold;
  margin: 0 0 15px;
  word-break: break-all;
}

.work-description {
  color: #ccc;
  line-height: 1.6;
  margin-bottom: 20px;
  white-space: pre-wrap;
  word-break: break-all;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.tag {
  background-color: #333;
  padding: 5px 12px;
  border-radius: 15px;
  font-size: 0.9rem;
}

.prompt-section {
  margin-bottom: 20px;
}

.prompt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.prompt-header h2 {
  font-size: 1.2rem;
  color: #aaa;
  margin: 0;
}

.prompt-actions {
  display: flex;
  gap: 10px;
}

.prompt-action-btn {
  background: none;
  border: 1px solid #444;
  color: #ccc;
  padding: 4px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 12px;
}

.prompt-action-btn:hover {
  background: #333;
  color: #fff;
}

.prompt-section h2 {
  font-size: 1.2rem;
  margin-bottom: 10px;
  color: #aaa;
}

.prompt-content {
  background-color: #222;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #333;
}

.prompt-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: rgba(224,245,255,.6);
  font-family: 'PingFang SC', sans-serif;
  font-size: 14px;
  font-weight: 500;
  line-height: 20px;
  letter-spacing: 0%;
  text-align: left;
  text-indent: 2em;
}

.ai-generated-label {
  color: rgba(184, 192, 201, 1);
  font-family: 'PingFang SC', sans-serif;
  font-size: 10px;
  font-weight: 400;
  line-height: 18px;
  letter-spacing: 0%;
  text-align: left;
  margin-bottom: 20px;
  display: block;
}

.stats {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #999;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1rem;
}

.stat-item.clickable {
  cursor: pointer;
  transition: color 0.3s;
}

.stat-item.clickable:hover {
  color: #f87171; /* red-400 */
}

.action-btn {
  border: none;
  cursor: pointer;
  font-weight: 600;
  font-size: 1rem;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.make-same {
  width: 212px;
  height: 34px;
  padding: 8px 21px;
  border-radius: 8px;
  background: linear-gradient(143.89deg, rgba(90, 238.5, 255, 1),rgba(53.76519012451172, 143.6488800048828, 227.73362731933594, 1) 41%,rgba(0, 83.60179138183594, 228.00489807128906, 1) 100%);
  color: white;
  justify-content: center;
  align-self: center;
}

.make-same:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .work-detail-page {
    height: auto;
    min-height: 100%;
    overflow: auto;
  }
  .detail-layout {
    flex-direction: column;
    height: auto;
  }
  .info-container {
    width: 100%;
    height: auto;
    border-left: none;
    border-top: 1px solid #2a2a2a;
  }
  .media-container {
    height: auto;
    padding: 20px;
    align-items: center;
  }
  .media-container img, .media-container video {
    max-height: 80vh;
  }
  .info-content, .actions-bar {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .info-content,
  .actions-bar {
    padding: 15px;
  }
  .media-container {
    height: auto;
    padding: 10px;
  }
  .actions-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  .action-btn {
    justify-content: center;
  }
}
</style>

