<template>
    <div class="container-xxl flex-grow-1 container-p-y">
        <search-bar @update:data="search" />
        <div class="row g-3">
            <div class="mt-8">
                <router-link to="/board/write">
                    <WriteButton />
                </router-link>
            </div>

            <board-card :posts="filteredList" @click="goDetail" />

            <div class="mt-8">
                <pagination />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import BoardCard from '@/components/list/BoardCardList.vue';
import Pagination from '@c/pagination/Pagination.vue';
import SearchBar from '@c/search/SearchBar.vue';
import router from '@/router';
import WriteButton from '@c/button/WriteBtn.vue';
import axios from '@api';

// 데이터 초기화
const list = ref([]);
const searchText = ref('');

// 상세 페이지 이동
const goDetail = (id) => {
    router.push({ name: 'BoardDetail', params: { id } });
};

// 검색 처리
const search = (e) => {
    searchText.value = e.trim();
};

// 검색 결과 필터링
const filteredList = computed(() =>
    list.value.filter((item) =>
        item.title.toLowerCase().includes(searchText.value.toLowerCase())
    )
);

// 게시물 데이터 로드
const fetchPosts = async () => {
    try {
        const response = await axios.get("board/general");
        if (response.data && Array.isArray(response.data.data)) {
            list.value = response.data.data.map((post) => ({
                ...post,
                img: post.img || null,
                likes: post.likes || 0,
                comments: post.comments || 0,
            }));
        }
    } catch (error) {
        console.error("Failed to fetch posts:", error);
    }
};

// 데이터 로드
onMounted(() => {
    fetchPosts();
});

</script>

<style>
/* 필요에 따라 스타일 추가 */
</style>
