<template>
  <div class="recommendations-container page-container">
    <div class="header-bar">
      <h2>为你推荐用户</h2>
      <p class="header-subtitle">根据你的兴趣，我们为你推荐了这些用户：</p>
    </div>

    <div v-if="isLoading" class="loading-message">
      <div class="spinner"></div>
      正在加载推荐...
    </div>
    <div v-if="fetchError" class="error-message">
      <p>{{ fetchError }}</p>
      <button @click="fetchRecommendedUsers" class="retry-button">重试</button>
    </div>
    
    <div v-if="!isLoading && recommendedUsers.length === 0 && !fetchError" class="empty-state">
      <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="currentColor" class="bi bi-emoji-frown" viewBox="0 0 16 16" style="margin-bottom: 15px; color: #6c757d;">
        <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/>
        <path d="M4.285 12.433a.5.5 0 0 0 .683-.183A3.5 3.5 0 0 1 8 10.5a3.5 3.5 0 0 1 3.032 1.75.5.5 0 0 0 .866-.5A4.5 4.5 0 0 0 8 9.5a4.5 4.5 0 0 0-3.898 2.25.5.5 0 0 0 .183.683M7 6.5C7 7.328 6.552 8 6 8s-1-.672-1-1.5S5.448 5 6 5s1 .672 1 1.5m4 0c0 .828-.448 1.5-1 1.5s-1-.672-1-1.5S9.448 5 10 5s1 .672 1 1.5"/>
      </svg>
      <p>暂时没有合适的推荐。</p>
      <p>可以尝试<router-link :to="{ name: 'UserProfile' }">完善你的兴趣标签</router-link>，帮助我们更好地为你匹配！</p>
    </div>

    <div v-if="recommendedUsers.length > 0" class="users-grid">
      <div v-for="user in recommendedUsers" :key="user.id" class="user-card">
        <router-link :to="{ name: 'UserProfileById', params: { id: user.id } }" class="user-link">
          <div class="user-avatar-wrapper">
            <img 
              v-if="user.avatar_url" 
              :src="user.avatar_url" 
              :alt="(user.nickname || user.email) + '头像'" 
              class="user-avatar"
              @error="setDefaultAvatar"
            />
            <div v-else class="user-avatar-placeholder">
              <span>{{ user.nickname ? user.nickname.charAt(0).toUpperCase() : (user.email ? user.email.charAt(0).toUpperCase() : 'U') }}</span>
            </div>
          </div>
          <div class="user-card-content">
            <h3 class="user-nickname">{{ user.nickname || user.email }}</h3>
            <p v-if="user.school" class="user-school">{{ user.school }}</p>
            <div v-if="user.common_interests_tags && user.common_interests_tags.length > 0" class="common-tags-section">
              <p class="common-tags-title">共同兴趣:</p>
              <div class="common-tags-preview">
                <span v-for="tag in user.common_interests_tags.slice(0, 3)" :key="tag.id" class="tag-chip">
                  {{ tag.name }}
                </span>
                <span v-if="user.common_interests_tags.length > 3" class="tag-chip more-tags">...</span>
              </div>
            </div>
             <p v-else class="no-common-tags">暂无明显共同兴趣</p>
          </div>
        </router-link>
      </div>
    </div>
    
    <!-- 推荐API通常不直接支持标准分页，除非后端特别实现 -->
    <!-- 
    <div v-if="pagination.totalPages > 1 && recommendedUsers.length > 0" class="pagination-controls">
      <button @click="fetchRecommendedUsers(pagination.currentPage - 1)" :disabled="!pagination.previous || isLoading">上一页</button>
      <span>第 {{ pagination.currentPage }} / {{ pagination.totalPages }}</span>
      <button @click="fetchRecommendedUsers(pagination.currentPage + 1)" :disabled="!pagination.next || isLoading">下一页</button>
    </div>
    -->
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import apiClient from '../services/api'; // 确保路径正确
import { useAuthStore } from '../store/auth'; // 确保路径正确
import { useRouter } from 'vue-router'; // 如果需要跳转

const recommendedUsers = ref([]);
const isLoading = ref(true);
const fetchError = ref('');
const authStore = useAuthStore();
const router = useRouter();

// 推荐API可能没有标准分页，所以pagination对象可能不完全适用
const pagination = reactive({
    currentPage: 1,
    // totalPages: 1, // 这些可能不需要了，取决于API
    // next: null,
    // previous: null,
    // count: 0,
});

const fetchRecommendedUsers = async () => {
  isLoading.value = true;
  fetchError.value = '';
  recommendedUsers.value = []; // 清空旧数据

  if (!authStore.isAuthenticated) {
    fetchError.value = '请先登录以获取个性化用户推荐。';
    isLoading.value = false;
    // 可以在这里引导用户去登录，或者依赖路由守卫
    // router.push({name: 'Login', query: {redirect: router.currentRoute.value.fullPath }});
    return;
  }

  try {
    // 调用我们后端已经测试通过的推荐API
    const response = await apiClient.get('accounts/users/recommendations/'); 

    // 推荐API返回的是一个直接的用户对象列表，每个用户对象包含了 common_interests_tags
    if (Array.isArray(response.data)) {
        recommendedUsers.value = response.data;
    } else {
        console.warn("推荐API返回数据格式非预期 (期望数组):", response.data);
        recommendedUsers.value = []; // 确保是数组
        fetchError.value = '获取推荐用户失败，数据格式不正确。';
    }
    
  } catch (error) {
    console.error('获取推荐用户列表失败:', error.response || error);
    if (error.response && error.response.status === 401) { // 未认证或Token过期
        fetchError.value = '会话已过期或无效，请重新登录以获取推荐。';
        // 触发登出并跳转到登录页是更完整的处理
        // authStore.logout();
        // router.push('/login');
    } else {
        fetchError.value = '无法加载推荐用户，请稍后重试。';
    }
  } finally {
    isLoading.value = false;
  }
};

const setDefaultAvatar = (event) => {
  // 尝试获取父级的占位符并显示
  const wrapper = event.target.closest('.user-avatar-wrapper');
  if(wrapper) {
    const placeholder = wrapper.querySelector('.user-avatar-placeholder');
    if (placeholder) placeholder.style.display = 'flex';
  }
  event.target.style.display = 'none'; // 隐藏加载失败的img
};

onMounted(() => {
  fetchRecommendedUsers();
});
</script>

<style scoped>
.page-container {
  padding-bottom: 40px; /* 为页脚留出空间 */
}
.recommendations-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}
.header-bar {
  text-align: center;
  margin-bottom: 30px;
}
.header-bar h2 {
  font-size: 2em;
  color: #333;
  margin-bottom: 5px;
}
.header-subtitle {
  font-size: 1em;
  color: #666;
}

.users-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); /* 调整卡片最小/最大宽度 */
  gap: 25px;
}
.user-card {
  border: 1px solid #e9ecef; /* 更淡的边框 */
  border-radius: 10px;
  background-color: #ffffff;
  padding: 20px;
  text-align: center;
  transition: transform 0.25s ease-in-out, box-shadow 0.25s ease-in-out;
  display: flex;
  flex-direction: column; /* 确保内容垂直排列 */
}
.user-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 10px 25px rgba(0, 20, 60, 0.1); /* 更明显的阴影 */
}
.user-link {
  text-decoration: none;
  color: inherit;
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-grow: 1; /* 使链接填满卡片 */
}
.user-avatar-wrapper {
  margin-bottom: 15px;
}
.user-avatar, .user-avatar-placeholder {
  width: 100px; /* 稍大一点的头像 */
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.8em;
  font-weight: 300; /* 稍细的占位符文字 */
  color: #adb5bd;
  border: 3px solid #fff;
  box-shadow: 0 2px 5px rgba(0,0,0,0.08);
}
.user-card-content {
  text-align: center;
  flex-grow: 1; /* 确保内容区也参与flex布局 */
}
.user-nickname {
  font-size: 1.2em;
  font-weight: 600;
  margin-bottom: 5px;
  color: #212529;
}
.user-school {
  font-size: 0.9em;
  color: #6c757d;
  margin-bottom: 10px;
}
.common-tags-section {
  margin-top: 10px;
}
.common-tags-title {
  font-size: 0.8em;
  color: #495057;
  margin-bottom: 5px;
  font-weight: 500;
}
.common-tags-preview {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 6px;
}
.tag-chip {
  background-color: #007bff; /* 蓝色标签 */
  color: white;
  font-size: 0.75em;
  padding: 4px 10px;
  border-radius: 15px;
  white-space: nowrap;
}
.tag-chip.more-tags {
    background-color: #6c757d; /* 灰色 '...' */
}
.no-common-tags {
    font-size: 0.8em;
    color: #adb5bd;
    margin-top: 10px;
    font-style: italic;
}

.loading-message, .error-message, .empty-state {
  text-align: center;
  padding: 50px 20px;
  color: #6c757d;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.empty-state p {
  margin-bottom: 8px;
}
.empty-state a {
  color: #007bff;
  font-weight: 500;
}
.spinner {
  border: 4px solid #f3f3f3; /* Light grey */
  border-top: 4px solid #3498db; /* Blue */
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.retry-button {
    margin-top: 15px;
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
/* 移除分页控件的样式，因为推荐API可能不分页 */
</style>