<template>
  <div class="home">
    <h1>AI Immersive Pet Companion</h1>
    <p>Experience the future of digital companionship</p>

    <!-- 未登录用户 -->
    <div v-if="!isLoggedIn" class="auth-section">
      <el-button type="primary" size="large" @click="goToLogin">Sign In</el-button>
      <el-button size="large" @click="goToRegister">Sign Up</el-button>
    </div>

    <!-- 已登录用户 - 聊天背景选择 -->
    <div v-else class="chat-backgrounds-section">
      <!-- 用户信息和快捷操作 -->
      <div class="user-actions">
        <div class="user-info">
          <span>欢迎回来，{{ userStore.userInfo?.nickname || userStore.userInfo?.username || '用户' }}!</span>
        </div>
        <div class="action-buttons">
          <el-button size="small" @click="goToProfile">
            <el-icon><UserFilled /></el-icon>
            个人中心
          </el-button>

          <el-button v-if="isAdmin" size="small" type="warning" @click="goToAdmin">
            <el-icon><Setting /></el-icon>
            管理后台
          </el-button>
          <el-button size="small" type="danger" @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </div>

      <!-- 选择聊天背景标题 -->
      <div class="section-title">
        <h2>选择你的聊天背景</h2>
        <p>点击任意背景开始与AI宠物聊天</p>
      </div>

      <!-- 背景网格 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="6" animated />
      </div>

      <div v-else-if="backgrounds.length === 0" class="empty-state">
        <el-empty description="暂无可用背景" />
      </div>

      <div v-else class="backgrounds-grid">
        <div
          v-for="background in backgrounds"
          :key="background.id"
          class="background-card"
          @click="enterChat(background)"
        >
          <div class="background-image">
            <!-- 视频背景 -->
            <video
              v-if="background.resource_type === 2"
              :src="background.resource_url"
              :alt="background.name"
              class="background-video"
              muted
              loop
              @mouseenter="handleVideoHover(true, $event)"
              @mouseleave="handleVideoHover(false, $event)"
            />
            <!-- 图片背景 -->
            <img
              v-else
              :src="background.thumbnail || background.resource_url"
              :alt="background.name"
              class="background-img"
            />

            <!-- 默认标识 -->
            <div v-if="background.is_default" class="default-badge">
              <el-tag type="success" size="small">默认</el-tag>
            </div>

            <!-- 悬浮遮罩 -->
            <div class="hover-overlay">
              <div class="hover-content">
                <el-icon class="chat-icon"><ChatDotRound /></el-icon>
                <span>开始聊天</span>
              </div>
            </div>
          </div>

          <div class="background-info">
            <h3>{{ background.name }}</h3>
            <p v-if="background.description" class="description">
              {{ background.description }}
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { Setting, SwitchButton, UserFilled, ChatLineRound, ChatDotRound } from '@element-plus/icons-vue'
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { backgroundAPI } from '@/api'

export default {
  name: 'HomeView',
  components: {
    Setting,
    SwitchButton,
    UserFilled,
    ChatLineRound,
    ChatDotRound
  },
  setup() {
    const userStore = useUserStore()
    const router = useRouter()

    // 响应式数据
    const backgrounds = ref([])
    const loading = ref(false)

    // 加载背景列表
    const loadBackgrounds = async () => {
      loading.value = true
      try {
        const response = await backgroundAPI.list({ page: 1, size: 100 })
        backgrounds.value = (response.data.data || []).map(bg => ({
          ...bg,
          is_default: false // TODO: 需要从后端获取用户的默认背景信息
        }))
      } catch (error) {
        console.error('Failed to load backgrounds:', error)
        backgrounds.value = []
      } finally {
        loading.value = false
      }
    }

    // 视频悬停处理
    const handleVideoHover = (isHover, event) => {
      const video = event.target
      if (isHover) {
        video.play()
      } else {
        video.pause()
      }
    }

    // 进入聊天
    const enterChat = (background) => {
      router.push({
        path: '/chat',
        query: { background_id: background.id }
      })
    }

    // 组件挂载
    onMounted(() => {
      if (userStore.accessToken) {
        loadBackgrounds()
      }
    })

    return {
      userStore,
      backgrounds,
      loading,
      isAdmin: computed(() => userStore.isAdmin),
      isLoggedIn: computed(() => !!userStore.accessToken),
      handleVideoHover,
      enterChat
    }
  },
  methods: {
    goToLogin() {
      this.$router.push('/login')
    },
    goToRegister() {
      this.$router.push('/register')
    },
    goToProfile() {
      this.$router.push('/profile')
    },

    goToAdmin() {
      this.$router.push('/admin')
    },
    async handleLogout() {
      try {
        const userStore = useUserStore()
        await userStore.logout()
        ElMessage.success('已退出登录')
        this.$router.push('/login')
      } catch (error) {
        console.error('Logout failed:', error)
        ElMessage.error('退出失败，请重试')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.home {
  padding: 40px 20px;
  max-width: 1400px;
  margin: 0 auto;
  text-align: center;

  h1 {
    font-size: 3rem;
    margin-bottom: 1rem;
    color: #303133;
  }

  p {
    font-size: 1.2rem;
    margin-bottom: 3rem;
    color: #606266;
  }
}

.auth-section {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-top: 60px;
}

.chat-backgrounds-section {
  margin-top: 40px;
}

.user-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .user-info {
    font-size: 16px;
    color: #303133;
    font-weight: 500;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.section-title {
  text-align: center;
  margin-bottom: 40px;

  h2 {
    font-size: 2rem;
    color: #303133;
    margin-bottom: 10px;
  }

  p {
    font-size: 1rem;
    color: #909399;
    margin: 0;
  }
}

.backgrounds-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  padding: 20px 0;
}

.background-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  &:hover {
    transform: translateY(-8px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  }

  .background-image {
    position: relative;
    width: 100%;
    height: 200px;
    overflow: hidden;

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

    .default-badge {
      position: absolute;
      top: 12px;
      left: 12px;
      z-index: 10;
    }

    .hover-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;

      .hover-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
        color: white;

        .chat-icon {
          font-size: 48px;
        }

        span {
          font-size: 16px;
          font-weight: 500;
        }
      }
    }

    &:hover .hover-overlay {
      opacity: 1;
    }
  }

  .background-info {
    padding: 16px;

    h3 {
      margin: 0 0 8px 0;
      font-size: 16px;
      color: #303133;
      font-weight: 500;
    }

    .description {
      margin: 0;
      font-size: 13px;
      color: #909399;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }
}

.loading-state {
  padding: 40px 0;
}

.empty-state {
  padding: 60px 20px;
}

// 响应式设计
@media (max-width: 768px) {
  .home {
    padding: 20px 10px;

    h1 {
      font-size: 2rem;
    }

    p {
      font-size: 1rem;
      margin-bottom: 2rem;
    }
  }

  .user-actions {
    flex-direction: column;
    gap: 16px;

    .action-buttons {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .section-title {
    h2 {
      font-size: 1.5rem;
    }
  }

  .backgrounds-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }
}
</style>
