<template>
  <div class="ai-user-profile">
    <div class="profile-container">
      <!-- 个人信息卡片 -->
      <div class="profile-card">
        <div class="profile-header">
          <div class="avatar-section">
            <div class="avatar-wrapper">
              <img v-if="isLoggedIn && userInfo?.avatarUrl" :src="userInfo.avatarUrl" :alt="userName"
                @error="handleAvatarError" class="avatar-img" />
              <img v-else :src="defaultAvatar" alt="默认头像" class="avatar-img" />
            </div>
          </div>
          <div class="user-info">
            <h2 class="user-name">{{ userName }}</h2>
            <p class="user-id">ID: {{ userId }}</p>
          </div>
        </div>
      </div>

      <!-- 个人作品列表 -->
      <div class="works-section">
        <div class="section-header">
          <div class="tab-switcher">
            <button :class="['tab-btn', { active: activeTab === 'published' }]" @click="switchTab('published')">
              广场作品
            </button>
            <button :class="['tab-btn', { active: activeTab === 'liked' }]" @click="switchTab('liked')">
              点赞作品
            </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="waterfallItems.length > 0"
          :items="waterfallItems"
          :loading="loading"
          :has-more="false"
          :show-carousel="false"
          :show-author="true"
          :show-stats="true"
          :show-toolbar="true"
          :is-logged-in="isLoggedIn"
          :field-map="waterfallFieldMap"
          :more-menu-action="activeTab === 'liked' ? 'unlike' : 'delete'"
          @view-detail="handleWorkClick"
          @make-same="handleMakeSame"
          @download="handleDownload"
          @share="handleShare"
          @share-wechat="handleShareWechat"
          @share-xiaohongshu="handleShareXiaohongshu"
          @share-link="handleShareLink"
          @copy-prompt="handleCopyPrompt"
          @delete="handleDelete"
          @unlike="handleUnlike"
          @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">{{ activeTab === 'published' ? '还没有作品，快去创作吧！' : '还没有点赞作品' }}</p>
          <button v-if="activeTab === 'published'" class="empty-create-btn" @click="handleCreateWork">
            开始创作
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 登录弹窗 -->
  <LoginModal v-if="showLoginModal" :visible="showLoginModal" mode="login" @login="handleLoginSuccess"
    @close="handleCloseLoginModal" />
</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 defaultAvatarImg from '../../assets/AI_APP/USER_AI/user_img.png'
import { getUserPublishedWorks, getUserLikedWorks, getWorkDetail } from '../../api'
import { unlikeWork } from '../../api/plaza'
import { deleteAITask } from '../../api/ai'
import WaterfallGrid from '@/components/WaterfallGrid.vue'

const router = useRouter()
const userStore = useUserStore()
const defaultAvatar = defaultAvatarImg

// 登录弹窗状态
const showLoginModal = ref(false)

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isLoggedIn = computed(() => userStore.getIsLoggedIn)
const userName = computed(() => isLoggedIn.value ? (userInfo.value?.username || userInfo.value?.phone || '用户') : '未登录')
const userId = computed(() => isLoggedIn.value ? (userInfo.value?.id || '000000') : '未登录')
const userPoints = computed(() => {
  if (!isLoggedIn.value) {
    return 0
  }
  return userInfo.value?.points || 0
})

// Tab切换状态
const activeTab = ref('published') // 'published' | 'liked'

// 作品数据
const works = ref([])
const likedWorks = ref([])
const loading = ref(true)

// 当前展示的作品列表
const currentWorks = computed(() => {
  return activeTab.value === 'published' ? works.value : likedWorks.value
})

const waterfallFieldMap = {
  key: 'id',
  mediaUrl: 'mediaUrl',
  title: 'title',
  author: 'authorInfo',
  avatar: 'avatarUrl',
  authorName: 'nickname',
  time: 'createdAt',
  viewCount: 'views',
  likeCount: 'likes',
  prompt: 'title',
  taskType: 'taskType'
}

const waterfallItems = computed(() =>
  currentWorks.value.map(work => ({
    ...work,
    mediaUrl: work.mediaUrl || work.coverUrl || work.referenceImageUrl,
    authorInfo: work.authorInfo || {
      avatarUrl: work.author?.avatarUrl || userInfo.value?.avatarUrl || defaultAvatar,
      nickname: work.author?.nickname || work.author?.name || userName.value
    },
    createdAt: work.createdAt || work.likedAt || work.likedTime || work.createTime
  }))
)

// 切换Tab
const switchTab = (tab) => {
  if (activeTab.value === tab) return
  activeTab.value = tab

  if (tab === 'published') {
    if (works.value.length === 0) {
      fetchWorks()
    }
  } else {
    if (likedWorks.value.length === 0) {
      fetchLikedWorks()
    }
  }
}

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

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

    let allWorks = [];
    if (response.code === 200 && response.data?.list) {
      // 过滤出视频类任务
      allWorks = response.data.list.filter(task =>
        task.taskType === 'text_to_video' || task.taskType === 'image_to_video'
      );
    } else {
      console.warn('fetchWorks: API响应格式不正确或未返回作品数据', response);
    }

    // 按创建时间降序排序
    allWorks.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))

    console.log('fetchWorks: API调用成功，筛选后作品数量:', allWorks.length);

    works.value = allWorks.map(task => {
      const mediaUrl = task.resultUrl || task.imageUrl || ''
      return {
      id: task.workNo,
      taskType: task.taskType,
      title: task.prompt,
      description: task.taskType === 'text_to_video' ? '文生视频' : task.taskType === 'image_to_video' ? '图生视频' : task.taskType === 'text_to_image' ? '文生图' : task.taskType === 'image_to_image' ? '图生图' : '分镜视频',
        coverUrl: task.resultUrl,
        referenceImageUrl: task.imageUrl,
        mediaUrl,
      createdAt: task.createTime,
        views: task.viewCount,
        likes: task.likeCount,
        authorInfo: {
          avatarUrl: userInfo.value?.avatarUrl || defaultAvatar,
          nickname: userName.value
        }
      }
    })

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

// 获取点赞作品列表
const fetchLikedWorks = async () => {
  console.log('fetchLikedWorks: 开始获取点赞作品');
  if (!isLoggedIn.value) {
    loading.value = false
    return
  }
  loading.value = true
  try {
    const params = {
      page: 1,
      size: 100
    }

    const response = await getUserLikedWorks(params);
    console.log('fetchLikedWorks: 收到API响应:', response);

    let allLikedWorks = [];
    if (response.code === 200 && response.data?.list) {
      allLikedWorks = response.data.list;
    } else if (response.code === 0 && response.data?.list) {
      // 兼容code=0的情况
      allLikedWorks = response.data.list;
    } else {
      console.warn('fetchLikedWorks: API响应格式不正确', response);
    }

    console.log('fetchLikedWorks: 点赞作品数量:', allLikedWorks.length);

    likedWorks.value = allLikedWorks.map(item => {
      // 判断是图片还是视频
      const isImage = item.taskType === 'text_to_image' || item.taskType === 'image_to_image';
      const isVideo = item.taskType === 'text_to_video' || item.taskType === 'image_to_video' || item.taskType === 'storyboard_to_video';

      const mediaUrl = isVideo ? item.resultUrl : (isImage ? item.resultUrl : (item.coverUrl || item.imageUrl || ''))
      const authorInfo = item.author ? {
        avatarUrl: item.author.avatarUrl || item.author.avatar || defaultAvatar,
        nickname: item.author.nickname || item.author.name || item.author.username || '创作者'
      } : {
        avatarUrl: defaultAvatar,
        nickname: '创作者'
      }

      return {
        id: item.workNo,
        likeId: item.likeId,
        taskType: item.taskType,
        title: item.title || item.prompt,
        description: item.taskType === 'text_to_video' ? '文生视频' :
          item.taskType === 'image_to_video' ? '图生视频' :
            item.taskType === 'text_to_image' ? '文生图' :
              item.taskType === 'image_to_image' ? '图生图' :
                item.taskType === 'storyboard_to_video' ? '分镜视频' : '未知',
        // 如果是图片类型，将resultUrl作为referenceImageUrl；如果是视频，作为coverUrl
        coverUrl: isVideo ? item.resultUrl : null,
        referenceImageUrl: isImage ? item.resultUrl : null,
        mediaUrl,
        createdAt: item.likedTime,
        views: item.viewCount,
        likes: item.likeCount,
        authorInfo,
        tags: item.tags || []
      }
    })

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

// 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) {
    if (activeTab.value === 'published') {
      fetchWorks()
    } else {
      fetchLikedWorks()
    }
  } else if (!isNowLoggedIn) {
    // 用户登出后，清空作品并停止加载
    works.value = []
    likedWorks.value = []
    loading.value = false
  }
})


// 获取头像文字
const getAvatarText = (name) => {
  if (!name) return '用'
  return name.charAt(0).toUpperCase()
}

// 处理头像错误
const handleAvatarError = (e) => {
  e.target.style.display = 'none'
}

// 编辑头像
const handleEditAvatar = () => {
  console.log('编辑头像')
  // TODO: 打开头像编辑弹窗
}

// 创建作品
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 handleDownload = async (work) => {
  try {
    const url = work.mediaUrl || work.coverUrl || work.referenceImageUrl
    if (!url) {
      ElMessage.warning('无可下载内容')
      return
    }

    ElMessage.info('正在下载...')

    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 copyShareLink = (url, successMessage) => {
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success(successMessage)
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

const buildShareUrl = (work) => `${globalThis.location.origin}/ai-application/work/${work.id}`

const handleShare = (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 handleShareLink = (work) => {
  handleShare(work)
}

// 删除作品
const handleDelete = async (work) => {
  if (!work || !work.id) {
    ElMessage.warning('作品信息无效')
    return
  }

  try {
    // 确认删除
    const confirmed = await new Promise((resolve) => {
      ElMessageBox.confirm(
        '确定要删除这个作品吗？删除后无法恢复。',
        '确认删除',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
      ).then(() => resolve(true)).catch(() => resolve(false))
    })

    if (!confirmed) {
      return
    }

    // 调用删除 API
    const response = await deleteAITask(work.id)
    
    if (response.code === 200 || response.code === 0) {
      ElMessage.success('删除成功')
      
      // 从列表中移除该作品
      if (activeTab.value === 'published') {
        works.value = works.value.filter(w => w.id !== work.id)
      } else {
        likedWorks.value = likedWorks.value.filter(w => w.id !== work.id)
      }
    } else {
      ElMessage.error(response.message || '删除失败，请稍后重试')
    }
  } catch (error) {
    console.error('删除作品失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 取消点赞
const handleUnlike = async (work) => {
  if (!work || !work.id) {
    ElMessage.warning('作品信息无效')
    return
  }

  try {
    // 调用取消点赞 API
    const response = await unlikeWork(work.id)
    
    if (response.code === 200 || response.code === 0) {
      ElMessage.success('已取消点赞')
      
      // 从点赞列表中移除该作品
      likedWorks.value = likedWorks.value.filter(w => w.id !== work.id)
    } else {
      ElMessage.error(response.message || '取消点赞失败，请稍后重试')
    }
  } 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('复制失败，请手动复制')
  })
}
</script>

<style scoped>
.ai-user-profile {
  width: 100%;
  min-height: calc(100vh - 80px);
  background: #151515;
  box-sizing: border-box;
  position: relative;
  display: block;
  overflow-y: auto;
  padding: 40px 0;
  /* 火狐浏览器兼容性修复 */
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
}

.profile-container {
  width: 100%;
  margin: 0;
  padding: 0 40px;
  box-sizing: border-box;
}

/* 个人信息卡片 */
.profile-card {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(15, 15, 15, 1);
  border-radius: 16px;
  padding: 40px;
  margin-bottom: 40px;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  -moz-backdrop-filter: blur(10px);
  height: 160px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  /* 火狐浏览器兼容性修复 */
  -moz-border-radius: 16px;
  -webkit-border-radius: 16px;
}

/* 左上角背景图 */
.profile-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -200px;
  width: 800px;
  height: 100%;
  background: url('../../assets/AI_APP/USER_AI/YOU.png') no-repeat center center;
  background-size: cover;
  z-index: 1;
  border-radius: 16px 0 0 16px;
  transition: all 0.3s ease;
}

/* 右下角背景图 */
.profile-card::after {
  content: '';
  position: absolute;
  bottom: 0;
  right: -200px;
  width: 800px;
  height: 100%;
  background: url('../../assets/AI_APP/USER_AI/LEFT.png') no-repeat center center;
  background-size: cover;
  z-index: 1;
  border-radius: 0 16px 16px 0;
  transition: all 0.3s ease;
}

.profile-header {
  display: flex;
  gap: 40px;
  align-items: center;
  position: relative;
  z-index: 2;
  height: 100%;
}

.avatar-section {
  position: relative;
  flex-shrink: 0;
}

.avatar-wrapper {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
}

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

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  font-weight: 600;
  color: #ffffff;
}


.user-info {
  flex: 1;
}

.user-name {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-weight: 400;
  font-size: 20px;
  line-height: 28px;
  letter-spacing: 0%;
  color: #ffffff;
  margin: 0 0 8px 0;
  text-align: left;
}

.user-id {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-weight: 400;
  font-size: 14px;
  line-height: 28px;
  letter-spacing: 0%;
  color: rgba(255, 255, 255, 0.5);
  margin: 0 0 24px 0;
  text-align: left;
}


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

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

/* Tab切换按钮 */
.tab-switcher {
  display: flex;
  gap: 12px;
  background: rgba(255, 255, 255, 0.05);
  padding: 4px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.tab-btn {
  padding: 8px 20px;
  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;
}

.tab-btn:hover {
  color: rgba(255, 255, 255, 0.8);
  background: rgba(255, 255, 255, 0.05);
}

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

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
  margin: 0;
}

.create-btn {
  height: 40px;
  padding: 0 20px;
  background: linear-gradient(135deg, #1AC3FF 0%, #0F9CFF 100%);
  border: none;
  border-radius: 20px;
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
  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-card:hover .play-icon-overlay {
  opacity: 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: 12px;
  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 16px;
  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;
}

.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%);
}

/* 个人主页：浏览/点赞徽标 */
.meta-badge {
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: flex;
  gap: 8px;
  background: rgba(10, 14, 39, 0.6);
  border: 1px solid rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  padding: 6px 8px;
  border-radius: 999px;
  z-index: 3;
}

.meta-item {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  color: #E2E8F0;
  font-size: 12px;
}

.play-icon-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.play-icon-overlay svg {
  width: 28px;
  height: 28px;
  margin-left: 4px;
  /*视觉居中*/
}

.work-info {
  padding: 16px;
}

.work-title {
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.work-desc {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.6);
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  height: 2.8em;
}

.work-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

/* 空状态 */
.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.5);
  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: #ffffff;
  font-size: 16px;
  font-weight: 500;
  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);
}

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

.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(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .ai-user-profile {
    min-height: calc(100vh - 70px);
    padding: 20px 0;
  }

  .profile-container {
    padding: 0 20px;
  }

  .profile-card {
    padding: 24px;
    height: 140px;
  }

  .profile-card::before {
    width: 400px;
    height: 140px;
    border-radius: 14px 0 0 14px;
  }

  .profile-card::after {
    width: 400px;
    height: 140px;
    border-radius: 0 14px 14px 0;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 24px;
  }

  .avatar-wrapper {
    width: 100px;
    height: 100px;
  }

  .user-name {
    font-size: 24px;
  }

  .user-stats {
    justify-content: center;
    gap: 24px;
  }

  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }

  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .ai-user-profile {
    min-height: calc(100vh - 60px);
    padding: 15px 0;
  }

  .profile-container {
    padding: 0 15px;
  }

  .profile-card {
    padding: 20px;
    height: 120px;
  }

  .profile-card::before {
    top: 10px;
    right: 10px;
    width: 50px;
    height: 50px;
    opacity: 0.2;
  }

  .profile-card::after {
    bottom: 10px;
    left: 10px;
    width: 35px;
    height: 35px;
    opacity: 0.1;
  }

  .user-name {
    font-size: 20px;
  }

  .stat-value {
    font-size: 20px;
  }

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