<template>
  <div class="ai-works-page">
    <div class="works-container">
      <!-- 作品列表 -->
      <div class="works-section">
        <div class="section-header">
          <!-- 分类筛选 -->
          <div class="category-filters">
            <button 
              v-for="category in categories" 
              :key="category.value"
              class="category-btn"
              :class="{ 'active': activeCategory === category.value }"
              @click="handleCategoryChange(category.value)"
            >
              {{ category.label }}
            </button>
          </div>
          <button class="create-btn" @click="handleCreateWork">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M8 3.33337V12.6667" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
              <path d="M3.33334 8H12.6667" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
            </svg>
            创建作品
          </button>
        </div>

        <div v-if="loading" class="loading-state">
          <div class="spinner"></div>
          <p>正在加载作品...</p>
        </div>

        <WaterfallGrid
          v-else-if="works.length > 0"
          :items="works"
          :loading="loading"
          :has-more="false"
          :show-carousel="false"
          :show-author="true"
          :show-stats="false"
          :show-toolbar="true"
          :is-logged-in="isLoggedIn"
          :field-map="waterfallFieldMap"
          :more-menu-action="'delete'"
          :more-menu-items="moreMenuItems"
          @view-detail="handleWorkClick"
          @make-same="handleMakeSame"
          @download="handleDownload"
          @delete="handleDelete"
          @publish="openPublishDialog"
          @copy-prompt="handleCopyPrompt"
          @share-link="handleShareLink"
          @share-wechat="handleShareWechat"
          @share-xiaohongshu="handleShareXiaohongshu"
          @need-login="showLoginModal = true"
        />

        <div v-else class="empty-state">
          <svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="40" cy="40" r="30" stroke="#1AC3FF" stroke-width="2" stroke-dasharray="4 4" opacity="0.3"/>
            <path d="M40 25V55M25 40H55" stroke="#1AC3FF" stroke-width="3" stroke-linecap="round" opacity="0.5"/>
          </svg>
          <p class="empty-text">还没有作品，快去创作吧！</p>
          <button class="empty-create-btn" @click="handleCreateWork">
            开始创作
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 登录弹窗 -->
  <LoginModal
    v-if="showLoginModal"
    :visible="showLoginModal"
    mode="login"
    @login="handleLoginSuccess"
    @close="handleCloseLoginModal"
  />

  <!-- 发布弹窗 -->
  <Teleport to="body">
    <transition name="modal">
      <div v-if="publishDialogVisible" class="publish-modal-overlay" @click="closePublishDialog">
        <div class="publish-modal-content" @click.stop>
          <div class="publish-modal-header">
            <h3>发布作品到广场</h3>
            <button class="publish-close-btn" @click="closePublishDialog">×</button>
          </div>
          <div class="publish-modal-body">
            <div class="form-item">
              <label for="publish-title">作品标题 <span class="required">*</span></label>
              <div class="input-wrapper">
                <input
                  id="publish-title"
                  v-model="publishForm.title"
                  type="text"
                  maxlength="50"
                  placeholder="请输入作品标题"
                />
                <span class="char-count">{{ publishForm.title.length }} / 50</span>
              </div>
            </div>
            <div class="form-item">
              <label for="publish-description">作品描述 <span class="required">*</span></label>
              <div class="textarea-wrapper">
                <textarea
                  id="publish-description"
                  v-model="publishForm.description"
                  maxlength="200"
                  rows="4"
                  placeholder="请输入作品描述"
                ></textarea>
                <span class="char-count">{{ publishForm.description.length }} / 200</span>
              </div>
            </div>
            <div class="form-item">
              <label for="publish-tag-input">作品标签 <span class="required">*</span></label>
              <div class="tags-container">
                <span
                  v-for="(tag, index) in publishForm.tags"
                  :key="tag + index"
                  class="tag-item"
                >
                  {{ tag }}
                  <button class="tag-remove" @click="removePublishTag(index)">×</button>
                </span>
                <input
                  id="publish-tag-input"
                  v-if="publishForm.tags.length < 5"
                  v-model="currentTagInput"
                  type="text"
                  maxlength="10"
                  placeholder="输入标签后回车"
                  @keyup="handlePublishTagKeyup"
                  class="tag-input"
                />
              </div>
              <div class="form-hint">最多 5 个标签，每个不超过 10 个字</div>
            </div>
          </div>
          <div class="publish-modal-footer">
            <button class="cancel-btn" @click="closePublishDialog">取消</button>
            <button class="confirm-btn" :disabled="publishLoading" @click="handlePublishConfirm">
              <span v-if="publishLoading">发布中...</span>
              <span v-else>确认发布</span>
            </button>
          </div>
        </div>
      </div>
    </transition>
  </Teleport>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useUserStore } from '../../store'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import LoginModal from '../../components/LoginModal.vue'
import { getAITaskList, deleteAITask, publishWork, getWorkDetail } from '../../api'
import WaterfallGrid from '@/components/WaterfallGrid.vue'

const router = useRouter()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

// 登录弹窗状态
const showLoginModal = ref(false)
const publishDialogVisible = ref(false)
const publishLoading = ref(false)
const publishForm = ref({
  taskNo: '',
  title: '',
  description: '',
  tags: [],
  isPublic: true
})
const currentTagInput = ref('')

// 用户信息
const isLoggedIn = computed(() => userStore.getIsLoggedIn)

// 作品数据
const works = ref([])
const allWorks = ref([]) // 存储所有作品
const loading = ref(true)
const hovered = ref('')

// 分类筛选
const activeCategory = ref('all')
const categories = ref([
  { label: '全部', value: 'all' },
  { label: '文生图', value: 'text_to_image' },
  { label: '图生图', value: 'image_to_image' },
  { label: '文生视频', value: 'text_to_video' },
  { label: '图生视频', value: 'image_to_video' }
])

const waterfallFieldMap = {
  key: 'id',
  mediaUrl: 'mediaUrl',
  title: 'title',
  author: 'authorInfo',
  avatar: 'avatarUrl',
  authorName: 'nickname',
  time: 'createdAt',
  viewCount: 'viewCount',
  likeCount: 'likeCount',
  prompt: 'title',
  taskType: 'taskType'
}
const moreMenuItems = computed(() => ([
  { action: 'publish', label: '投稿', icon: 'publish' },
  { action: 'delete', label: '删除', icon: 'delete' }
]))

// 获取作品列表
const fetchWorks = async () => {
  console.log('fetchWorks: 开始获取作品，当前登录状态:', isLoggedIn.value);
  if (!isLoggedIn.value) {
    loading.value = false
    return
  }
  loading.value = true
  try {
    const params = { 
      status: 'completed',
      page:1,
      size:100
    }

    // 获取所有已完成的任务
    const response = await getAITaskList(params);
    console.log('fetchWorks: 收到API响应:', response);

    let taskList = [];
    if (response.code === 200 && response.data?.list) {
      // 获取所有任务（不再只过滤视频）
      taskList = response.data.list;
    } else {
      console.warn('fetchWorks: API响应格式不正确或未返回作品数据', response);
    }

    // 按创建时间降序排序
    taskList.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    
    console.log('fetchWorks: API调用成功，作品数量:', taskList.length);

    // 保存所有作品
    allWorks.value = taskList.map(task => {
      // 判断是图片还是视频
      const isImage = task.taskType === 'text_to_image' || task.taskType === 'image_to_image';
      const isVideo = task.taskType === 'text_to_video' || task.taskType === 'image_to_video' || task.taskType === 'storyboard_to_video';
      
      return {
        id: task.taskNo,
        taskType: task.taskType,
        title: task.promptSnippet,
        description: task.taskType === 'text_to_video' ? '文生视频' : 
                     task.taskType === 'image_to_video' ? '图生视频' : 
                     task.taskType === 'text_to_image' ? '文生图' : 
                     task.taskType === 'image_to_image' ? '图生图' : 
                     task.taskType === 'storyboard_to_video' ? '分镜视频' : '未知',
        // 如果是图片类型，将resultUrl作为referenceImageUrl；如果是视频，作为coverUrl
        coverUrl: isVideo ? task.resultUrl : null,
        referenceImageUrl: isImage ? task.resultUrl : task.imageUrl,
        mediaUrl: task.resultUrl || task.imageUrl,
        createdAt: task.createTime,
        authorInfo: {
          avatarUrl: userInfo.value?.avatarUrl || '',
          nickname: userInfo.value?.nickname || userInfo.value?.username || userInfo.value?.phone || '用户'
        }
      }
    })

    // 应用当前分类筛选
    filterWorksByCategory()

  } catch (error) {
    console.error('fetchWorks: 获取作品列表失败:', error)
    ElMessage.error('获取作品列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 根据分类筛选作品
const filterWorksByCategory = () => {
  if (activeCategory.value === 'all') {
    works.value = allWorks.value
  } else {
    works.value = allWorks.value.filter(work => work.taskType === activeCategory.value)
  }
}

// 处理分类切换
const handleCategoryChange = (category) => {
  activeCategory.value = category
  filterWorksByCategory()
}

// onMounted 和 watch 结合，确保登录后能加载作品
onMounted(() => {
  console.log('onMounted: 组件已挂载，初始登录状态:', isLoggedIn.value);
  if (isLoggedIn.value) {
    fetchWorks()
  } else {
    // 如果初始未登录，将 loading 设置为 false，显示空状态
    loading.value = false
  }
})

// 监听登录状态变化
watch(isLoggedIn, (isNowLoggedIn, wasLoggedIn) => {
  console.log(`watch(isLoggedIn): 登录状态变化，之前: ${wasLoggedIn}, 现在: ${isNowLoggedIn}`);
  // 仅在用户从"未登录"变为"已登录"时获取作品
  if (isNowLoggedIn && !wasLoggedIn) {
    fetchWorks()
  } else if (!isNowLoggedIn) {
    // 用户登出后，清空作品并停止加载
    works.value = []
    loading.value = false
  }
})

// 创建作品
const handleCreateWork = () => {
  // 检查登录状态
  if (!isLoggedIn.value) {
    showLoginModal.value = true
    return
  }
  
  // 跳转到创作页面
  router.push('/ai-application/create')
}

// 登录成功后的处理
const handleLoginSuccess = () => {
  showLoginModal.value = false
  ElMessage.success('登录成功，即将跳转到创作页面')
  // 延迟跳转，让用户看到成功提示
  setTimeout(() => {
    router.push('/ai-application/create')
  }, 500)
}

// 关闭登录弹窗
const handleCloseLoginModal = () => {
  showLoginModal.value = false
}

// 作品点击
const handleWorkClick = (work) => {
  if (work.id) {
    router.push({ name: 'AIApplicationWorkDetail', params: { id: work.id } })
  }
}

// 做同款 - 先获取详情数据，再跳转
const handleMakeSame = async (work) => {
  console.log('做同款:', work)

  try {
    // 显示加载提示
    const loadingMsg = ElMessage.info('正在准备数据...')

    // 获取完整的作品详情
    const res = await getWorkDetail(work.id)
    if (res?.code !== 200 || !res.data) {
      ElMessage.error('获取作品详情失败')
      return
    }

    const detailWork = res.data
    console.log('获取到的详情数据:', detailWork)

    // 关闭加载提示
    loadingMsg.close()

    // 根据任务类型跳转到对应的创作页面
    const taskType = detailWork.taskType
    let routePath = ''
    let query = {}

    // 根据任务类型判断跳转路由和参数
    switch (taskType) {
      case 'text_to_video':
        // 文生视频 - 跳转到 Create.vue，模式为 text
        routePath = '/ai-application/create'
        query.mode = 'text'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        if (detailWork.modelName) {
          query.modelName = detailWork.modelName
        }
        break

      case 'image_to_video':
        // 图生视频 - 跳转到 Create.vue，模式为 image
        routePath = '/ai-application/create'
        query.mode = 'image'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.imageUrl) {
          query.imageUrl = detailWork.imageUrl
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        if (detailWork.modelName) {
          query.modelName = detailWork.modelName
        }
        break

      case 'text_to_image':
        // 文生图 - 跳转到 ImageCreate.vue
        routePath = '/ai-application/image-create'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.imageUrl) {
          query.imageUrl = detailWork.imageUrl
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        break

      case 'storyboard_video':
      case 'storyboard_to_video':
        // 分镜视频 - 跳转到 Create.vue，模式为 storyboard
        routePath = '/ai-application/create'
        query.mode = 'storyboard'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.imageUrl) {
          query.imageUrl = detailWork.imageUrl
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
        break

      default:
        // 默认跳转到创作页面
        routePath = '/ai-application/create'
        query.mode = 'text'
        if (detailWork.prompt) {
          query.prompt = detailWork.prompt
        }
        if (detailWork.aspectRatio) {
          query.aspectRatio = detailWork.aspectRatio
        }
    }

    console.log('跳转参数:', { path: routePath, query })

    // 跳转到创作页面
    router.push({
      path: routePath,
      query: query
    })

    ElMessage.success('正在为您跳转到创作页面...')
  } catch (error) {
    console.error('做同款失败:', error)
    ElMessage.error(error.response?.data?.message || '操作失败，请重试')
  }
}

// 设置卡片引用
const setCardRef = (id, el) => {
  if (el) {
    cardRefs.value.set(id, el)
  } else {
    cardRefs.value.delete(id)
  }
}

// 设置视频引用
const setVideoRef = (id, el) => {
  if (el) {
    videoRefs.value.set(id, el)
  } else {
    videoRefs.value.delete(id)
  }
}

// 处理媒体加载
const handleMediaLoad = (event, workId) => {
  const target = event.target
  let width, height
  
  if (target.tagName === 'IMG') {
    width = target.naturalWidth
    height = target.naturalHeight
  } else if (target.tagName === 'VIDEO') {
    width = target.videoWidth
    height = target.videoHeight
  }
  
  if (width && height) {
    mediaDimensions.value.set(workId, { width, height })
    calculateCardHeight(workId)
  }
}

// 处理占位符加载 - 给一个默认的方形比例
const handlePlaceholderLoad = (workId) => {
  // 占位符使用 1:1 的方形比例
  mediaDimensions.value.set(workId, { width: 1, height: 1 })
  calculateCardHeight(workId)
}

// 计算卡片高度
const calculateCardHeight = (workId) => {
  const card = cardRefs.value.get(workId)
  if (!card) return

  const dimensions = mediaDimensions.value.get(workId)
  if (!dimensions) return

  const rowHeight = 10
  const gap = 20
  const maxCardHeight = 600
  const minCardHeight = 200

  const cardWidth = card.offsetWidth
  const aspectRatio = dimensions.height / dimensions.width
  let cardHeight = cardWidth * aspectRatio

  const isLandscape = dimensions.width > dimensions.height
  const effectiveMinHeight = isLandscape
    ? Math.max(minCardHeight, cardWidth * 0.5)
    : minCardHeight

  if (cardHeight > maxCardHeight) {
    cardHeight = maxCardHeight
  } else if (cardHeight < effectiveMinHeight) {
    cardHeight = effectiveMinHeight
  }

  const rowSpan = Math.ceil((cardHeight + gap) / (rowHeight + gap))
  card.style.gridRowEnd = `span ${rowSpan}`
  card.style.height = `${cardHeight}px`
}

// 卡片悬停处理 - 自动播放视频
const handleDownload = async (work) => {
  try {
    const url = work.mediaUrl || work.coverUrl || work.referenceImageUrl
    if (!url) {
      ElMessage.warning('无可下载内容')
      return
    }

    ElMessage.info('正在下载...')
    
    // 创建一个隐藏的 a 标签来触发下载
    const link = document.createElement('a')
    link.href = url
    link.download = `work_${work.id}_${Date.now()}`
    link.target = '_blank'
    document.body.appendChild(link)
    link.click()
    link.remove()

    ElMessage.success('下载已开始')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  }
}

// 复制提示词
const handleCopyPrompt = (work, prompt) => {
  if (!prompt) {
    ElMessage.warning('暂无提示词')
    return
  }
  navigator.clipboard.writeText(prompt).then(() => {
    ElMessage.success('提示词已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 构建分享链接
const buildShareUrl = (work) => {
  return `${globalThis.location.origin}/ai-application/work/${work.id}`
}

// 复制分享链接
const copyShareLink = (url, successMessage) => {
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success(successMessage || '链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 分享链接
const handleShareLink = (work) => {
  if (!work || !work.id) {
    ElMessage.warning('作品信息无效')
    return
  }
  copyShareLink(buildShareUrl(work), '链接已复制到剪贴板')
}

// 分享到微信
const handleShareWechat = (work) => {
  if (!work || !work.id) {
    ElMessage.warning('作品信息无效')
    return
  }
  const url = `${buildShareUrl(work)}?source-scene=shared&source-media=shared_wechat`
  copyShareLink(url, '微信分享链接已复制')
}

// 分享到小红书
const handleShareXiaohongshu = (work) => {
  if (!work || !work.id) {
    ElMessage.warning('作品信息无效')
    return
  }
  const url = `${buildShareUrl(work)}?source-media=shared_xiaohongshu`
  copyShareLink(url, '小红书分享链接已复制')
}

// 删除作品
const handleDelete = async (work) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个作品吗？删除后将无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除 API
    const response = await deleteAITask(work.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 从列表中移除已删除的作品
      works.value = works.value.filter(w => w.id !== work.id)
      allWorks.value = allWorks.value.filter(w => w.id !== work.id)
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

const openPublishDialog = (work) => {
  publishForm.value = {
    taskNo: work.id,
    title: work.title || '',
    description: work.description || '',
    tags: [],
    isPublic: true
  }
  currentTagInput.value = ''
  publishDialogVisible.value = true
}

const closePublishDialog = () => {
  publishDialogVisible.value = false
  publishLoading.value = false
}

const addPublishTag = () => {
  const tag = currentTagInput.value.trim()
  if (!tag) return
  if (publishForm.value.tags.length >= 5) {
    ElMessage.warning('最多添加5个标签')
    return
  }
  if (publishForm.value.tags.includes(tag)) {
    ElMessage.warning('标签已存在')
    return
  }
  publishForm.value.tags.push(tag)
  currentTagInput.value = ''
}

const removePublishTag = (index) => {
  publishForm.value.tags.splice(index, 1)
}

const handlePublishTagKeyup = (event) => {
  if (event.key === 'Enter') {
    event.preventDefault()
    addPublishTag()
  }
}

const handlePublishConfirm = async () => {
  if (!publishForm.value.title.trim()) {
    ElMessage.warning('请输入作品标题')
    return
  }
  if (!publishForm.value.description.trim()) {
    ElMessage.warning('请输入作品描述')
    return
  }
  if (publishForm.value.tags.length === 0) {
    ElMessage.warning('请至少添加一个标签')
    return
  }

  publishLoading.value = true
  try {
    const response = await publishWork({
      taskNo: publishForm.value.taskNo,
      title: publishForm.value.title.trim(),
      description: publishForm.value.description.trim(),
      tags: publishForm.value.tags,
      isPublic: publishForm.value.isPublic
    })
    if (response.code === 200) {
      ElMessage.success('发布成功，作品已提交审核')
      closePublishDialog()
      fetchWorks()
    } else {
      throw new Error(response.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error(error.message || '发布失败，请重试')
  } finally {
    publishLoading.value = false
  }
}
</script>

<style scoped>
.ai-works-page {
  width: 100%;
  min-height: calc(100vh - 80px);
  background: #151515;
  color: #ffffff;
  padding: 40px;
  box-sizing: border-box;
  overflow-y: auto;
}

.works-container {
  width: 100%;
  max-width: 1600px;
  margin: 0 auto;
}

/* 作品区域 */
.works-section {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 16px;
  padding: 32px;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 20px;
}

.category-filters {
  display: flex;
  gap: 8px;
  
  padding: 4px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.category-btn {
  padding: 8px 16px;
  background: transparent;
  border: none;
  border-radius: 8px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.category-btn:hover {
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
}

.category-btn.active {
  background: linear-gradient(135deg, #1AC3FF 0%, #0F9CFF 100%);
  color: #000;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(26, 195, 255, 0.3);
}

.create-btn {
  height: 40px;
  padding: 0 20px;
  background: linear-gradient(135deg, #1AC3FF 0%, #0F9CFF 100%);
  border: none;
  border-radius: 20px;
  color: #000;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.create-btn:hover {
  background: linear-gradient(135deg, #33DDE5 0%, #1AC3FF 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(26, 195, 255, 0.4);
}

/* 作品网格 - 瀑布流布局（CSS Grid）*/
.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  grid-auto-rows: 10px;
  align-items: start;
}

.work-card {
  background: transparent;
  border-radius: 12px;
  overflow: visible;
  border: none;
  box-shadow: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-height: 200px;
  max-height: 600px;
  position: relative;
  z-index: 1;
}

.work-cover {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background: #1e293b;
  overflow: hidden;
  border-radius: 12px;
  border: 1px solid #334155;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
}

.work-card:hover .work-cover {
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.5);
}

/* 任务类型标签 - 统一毛玻璃背景 */
.task-type-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  padding: 5px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  background: rgba(30, 41, 59, 0.4);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.25);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 2;
  transition: all 0.3s ease;
}

.work-card:hover .task-type-badge {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
  border-color: rgba(255, 255, 255, 0.3);
}

/* Hover 工具栏 - 与PlazaHome统一 */
.hover-toolbar {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  height: 44px;
  margin-top: -1px;
  opacity: 0;
  transform: translateY(0);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(66, 66, 66, 0.7);
  backdrop-filter: blur(100px);
  -webkit-backdrop-filter: blur(100px);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-top: 1px solid rgba(255, 255, 255, 0.05);
  border-radius: 0 0 12px 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  z-index: 5;
  pointer-events: none;
}

.hover-toolbar.visible {
  opacity: 1;
  pointer-events: auto;
}

.toolbar-prompt {
  flex: 1;
  color: rgba(255, 255, 255, 0.85);
  font-size: 12px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 8px;
  font-weight: 400;
}

.toolbar-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: #ffffff;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
  white-space: nowrap;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.toolbar-btn:hover {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.toolbar-btn svg {
  flex-shrink: 0;
}

.delete-btn {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

.delete-btn:hover {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}

.work-cover-img,
.work-cover-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.work-cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, rgba(26, 195, 255, 0.1) 0%, rgba(15, 156, 255, 0.1) 100%);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
}

.empty-text {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.65);
  margin: 24px 0;
}

.empty-create-btn {
  height: 44px;
  padding: 0 32px;
  background: linear-gradient(135deg, #1AC3FF 0%, #0F9CFF 100%);
  border: none;
  border-radius: 22px;
  color: #000;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.empty-create-btn:hover {
  background: linear-gradient(135deg, #33DDE5 0%, #1AC3FF 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(26, 195, 255, 0.4);
}

.publish-modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3000;
}

.publish-modal-content {
  width: min(460px, 90vw);
  background: rgba(21, 21, 21, 0.95);
  border-radius: 16px;
  padding: 24px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
}

.publish-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.publish-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #fff;
}

.publish-close-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.08);
  color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.publish-modal-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item label {
  display: block;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.85);
  margin-bottom: 6px;
}

.required {
  color: #ff6b6b;
  margin-left: 4px;
}

.input-wrapper,
.textarea-wrapper {
  position: relative;
  width: 100%;
}

.input-wrapper input,
.textarea-wrapper textarea {
  width: 100%;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.02);
  color: #fff;
  padding: 10px 12px;
  font-size: 14px;
  box-sizing: border-box;
}

.char-count {
  position: absolute;
  right: 10px;
  bottom: 6px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  min-height: 44px;
  background: rgba(255, 255, 255, 0.02);
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 999px;
  background: rgba(26, 195, 255, 0.1);
  color: #1ac3ff;
  font-size: 13px;
}

.tag-remove {
  border: none;
  background: transparent;
  color: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  font-size: 14px;
}

.tag-input {
  border: none;
  background: transparent;
  color: #fff;
  flex: 1;
  min-width: 100px;
  outline: none;
}

.form-hint {
  margin-top: 4px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

.publish-modal-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.publish-modal-footer .cancel-btn,
.publish-modal-footer .confirm-btn {
  min-width: 100px;
  border: none;
  border-radius: 999px;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
}

.publish-modal-footer .cancel-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.publish-modal-footer .confirm-btn {
  background: linear-gradient(135deg, #1ac3ff 0%, #0f9cff 100%);
  color: #000;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: rgba(255, 255, 255, 0.7);
}

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

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 1200px) {
  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 12px;
  }
}

@media (max-width: 1024px) {
  .category-filters {
    gap: 4px;
    padding: 3px;
  }

  .category-btn {
    padding: 6px 12px;
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .ai-works-page {
    padding: 20px;
  }

  .section-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .category-filters {
    width: 100%;
    justify-content: space-between;
    overflow-x: auto;
    flex-wrap: nowrap;
  }

  .category-btn {
    flex: 1;
    min-width: fit-content;
    padding: 8px 12px;
    font-size: 12px;
  }

  .create-btn {
    width: 100%;
    justify-content: center;
  }

  .works-section {
    padding: 20px;
  }
}
</style>
