<template>
    <div class="post-page-container">
        <!-- 顶部横向分类按钮 -->
        <div class="category-buttons-horizontal" ref="categoryBarRef">
            <button
                v-for="(category, index) in categories"
                :key="index"
                class="category-button"
                :class="{ active: selectedCategory === category }"
                @click="selectCategory(category)"
            >
                {{ category }}
            </button>
        </div>

        <!-- 帖子列表 -->
        <div class="post-list">
            <div
                v-for="(post, index) in postListStore.posts"
                :key="index"
                class="post-item"
                @click="goToPostDetail(post.id)"
            >
                <!-- 头像+用户名 -->
                <div class="post-header">
                    <img 
                        :src="(post.userName === '匿名用户' || post?.status === 1) 
                            ? require('@/assets/default-avatar/boy_4.png') 
                            : post.avatar || require('@/assets/default-avatar/boy_1.png')" 
                        alt="头像" 
                        class="post-avatar" 
                    />
                    <span class="post-username">{{ post.userName }}</span>
                </div>
                <!-- 标题 -->
                <div class="post-title">{{ post.title }}</div>
                <!-- 图片 -->
                <div v-if="post.image" class="post-image-wrapper">
                    <img :src="post.image" alt="帖子图片" class="post-image" />
                </div>
                <!-- 统计信息 -->
                <div class="post-stats">
                    <span>👁 {{ post.viewCount }}</span>
                    <span>🗨 {{ post.comments }}</span>
                    <span>♥ {{ post.likes }}</span>
                </div>
                <!-- 发布时间 -->
                <div class="post-time">
                    {{ post.createTime ? post.createTime.slice(0, 10) : '' }}
                </div>
            </div>
        </div>

        <!-- 回到顶部按钮 -->
        <button
            v-if="showBackToTop"
            class="back-to-top-btn"
            @click="scrollToTop"
        >
            🔝
        </button>
    </div>
</template>

<script setup lang="js" name="PostPage">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { usePostListStore } from '@/stores/postlist.js';

const categoryMap = [
  { name: '全部', id: null },
  { name: '校园活动', id: 1 },
  { name: '学习', id: 2 },
  { name: '娱乐', id: 3 },
  { name: '二手交易', id: 4 }
];
const categories = ref(categoryMap.map(item => item.name));
const selectedCategory = ref('全部');
const postListStore = usePostListStore();
const router = useRouter();

const categoryBarRef = ref(null);
const showBackToTop = ref(false);

const selectCategory = async (categoryName) => {
  selectedCategory.value = categoryName;
  postListStore.resetList();
  const categoryObj = categoryMap.find(item => item.name === categoryName);
  await postListStore.getList(categoryObj ? categoryObj.id : null);
};

const goToPostDetail = (postId) => {
  router.push({ name: 'PostDetail', params: { id: postId } });
};

const handleScroll = async () => {
  const scrollContainer = document.documentElement;
  // 判断分类栏底部是否已经滚出视口
  const bar = categoryBarRef.value;
  if (bar) {
    const rect = bar.getBoundingClientRect();
    showBackToTop.value = rect.bottom < 0;
  } else {
    // 兜底：滚动超过200px也显示
    showBackToTop.value = scrollContainer.scrollTop > 200;
  }
  // 触底加载
  if (
    scrollContainer.scrollTop + window.innerHeight >= scrollContainer.scrollHeight - 10 &&
    !postListStore.loading &&
    !postListStore.finished
  ) {
    const categoryObj = categoryMap.find(item => item.name === selectedCategory.value);
    await postListStore.getList(categoryObj ? categoryObj.id : null);
  }
};

const scrollToTop = () => {
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

onMounted(async () => {
  await postListStore.getList();
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});

watch(selectedCategory, () => {
  window.scrollTo(0, 0);
});
</script>

<style scoped>
.post-page-container {
    display: flex;
    background-color: rgba(249, 227, 238, 0.8);
    flex-direction: column;
    align-items: stretch;
    padding: 5px 0;
    box-sizing: border-box;
    gap: 1px;
    width: 100%;
}

/* 顶部横向分类按钮样式 */
.category-buttons-horizontal {
    display: flex;
    flex-direction: row;
    gap: 0;
    width: 100%;
    margin-bottom: 10px;
    border-bottom: 1px solid #eee;
    background: rgba(218, 213, 213, 0.6);
    padding-bottom: 2px;
}

.category-button {
    padding: 10px 24px;
    font-size: 14px;
    border: none;
    background-color: transparent;
    cursor: pointer;
    transition: background-color 0.3s, color 0.3s;
    color: #333;
    border-bottom: 2px solid transparent;
    outline: none;
}

.category-button.active {
    background-color: #f6fff8;
    color: #5aa76f;
    border-bottom: 2px solid #5aa76f;
    font-weight: bold;
}

.category-button:hover {
    background-color: #f0f0f0;
}

/* 帖子列表区域占满父容器，左右margin为10px */
.post-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 15px;
    padding: 10px; 
    flex: 1;
    width: 100%;
    box-sizing: border-box;
}

/* 帖子卡片自适应宽度和高度 */
.post-item {
    position: relative;
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    background-color: #ffffff;
    cursor: pointer;
    transition: box-shadow 0.3s;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    box-sizing: border-box;
    width: 100%;
    height: 280px;
    max-width: 100%;
    overflow: hidden;
}

/* 头像+用户名 */
.post-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 6px;
}

.post-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%; 
    object-fit: cover;
}

.post-username {
    font-size: 15px;
    color: #5aa76f;
    font-weight: bold;
}

/* 标题 */
.post-title {
    font-size: 18px;
    text-align: left;
    font-weight: bold;
    margin: 0 0 8px 0;
    color: #333;
    word-break: break-all;
    padding-left: 30px;
}

/* 图片展示 */
.post-image-wrapper {
    width: 100%;
    height: 160px; 
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
    overflow: hidden;
}
.post-image {
    width: 100%;
    height: 100%;
    object-fit: contain; 
    display: block;
}

/* 帖子统计信息样式 */
.post-stats {
    display: flex;
    gap: 15px;
    font-size: 16px;
    color: #999;
    position: absolute;
    bottom: 5px;
    left: 15px;
}

/* 发布时间（右下角） */
.post-time {
    position: absolute;
    bottom: 5px;
    right: 15px;
    font-size: 13px;
    color: #bbb;
}

/* 回到顶部按钮样式 */
.back-to-top-btn {
    position: fixed;
    right: 32px;
    bottom: 48px;
    z-index: 999;
    background: #d5e9da;
    color: #fff;
    border: none;
    border-radius: 5px;
    font-size: 36px;
    box-shadow: 0 2px 8px rgba(90,167,111,0.15);
    cursor: pointer;
    opacity: 0.85;
    transition: opacity 0.2s;
}
.back-to-top-btn:hover {
    opacity: 1;
    background: #388e3c;
}
</style>