<template>
    <div class="container-xxl flex-grow-1 container-p-y">
        <div class="row">
            <div class="col">
                <div class="card">
                    <!-- 프로필 헤더 -->
                    <div class="card-header">
                        <BoardProfile
                            :boardId="currentBoardId"
                            :profileName="profileName"
                            class="pb-6 border-bottom"
                            />
                    </div>
                    <!-- 게시글 내용 -->
                    <div class="card-body">
                        <h5 class="mb-4">{{ boardTitle }}</h5>
                        <!-- HTML 콘텐츠 렌더링 -->
                        <div class="board-content text-body" style="line-height: 1.6;" v-html="$common.contentToHtml(boardContent)">

                        </div>
                        
                        <!-- 좋아요 버튼 -->
                        <div class="row justify-content-center my-10">
                            <BoardRecommendBtn
                                :bigBtn="true"
                                :boardId="currentBoardId"
                                :commentId="null"
                                :likeCount="currentLikeCount"
                                :dislikeCount="currentDislikeCount"
                                @updateReaction="handleUpdateReaction"
                            />
                        </div>

                        <!-- 첨부파일 목록 -->
                        <ul v-if="attachments.length" class="attachments mt-4 list-unstyled">
                            <li v-for="(attachment, index) in attachments" :key="index" class="mb-2">
                                <a :href="attachment.url" target="_blank" class="text-decoration-none">{{ attachment.name }}</a>
                            </li>
                        </ul>

                        <!-- 댓글 영역 -->
                        <BoardComentArea :comments="comments" />

                        <!-- 수정 버튼 -->
                        <!-- <button class="btn btn-primary" @click="goToEditPage">
                            글 수정
                        </button> -->
                    </div>
                    <div class="card-footer">
                        <BoardCommentList/>

                        <Pagination/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import BoardComentArea from '@c/board/BoardComentArea.vue';
import BoardProfile from '@c/board/BoardProfile.vue';
import BoardCommentList from '@/components/board/BoardCommentList.vue';
import BoardRecommendBtn from '@/components/button/BoardRecommendBtn.vue';
import Pagination from '@/components/pagination/Pagination.vue';
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from '@api';

// 게시물 데이터 상태
const profileName = ref('익명 사용자');
const boardTitle = ref('제목 없음');
const boardContent = ref('');
const comments = ref([]);
const attachments = ref([]);

// 라우트에서 ID 가져오기
const route = useRoute();
const router = useRouter();
const currentBoardId = ref(Number(route.params.id));

// 글 수정 페이지로 이동
const goToEditPage = () => {
    router.push({ name: 'BoardEdit', params: { id: currentBoardId.value } });
};

// 게시물 상세 데이터 불러오기
const fetchBoardDetails = async () => {
    try {
        const response = await axios.get(`board/${currentBoardId.value}`);
        const data = response.data.data;

        // API 응답 데이터 반영
        const boardDetail = data.boardDetail || {};
        profileName.value = boardDetail.author || '익명 사용자';
        boardTitle.value = boardDetail.title || '제목 없음';
        boardContent.value = boardDetail.content || '';

        attachments.value = data.attachments || [];
        comments.value = data.comments || [];
    } catch (error) {
        console.error('게시물 가져오기 오류:', error);
        alert('게시물 데이터를 불러오는 중 오류가 발생했습니다.');
    }
};

const currentLikeCount = ref(10);
const currentDislikeCount = ref(2);

// 좋아요, 싫어요
const handleUpdateReaction = async ({ type, boardId, commentId }) => {
    try {
        const cmtId = commentId !== null ? commentId : 0;
        console.log(`Sending reaction: type=${type}, boardId=${boardId}, commentId=${cmtId}`);
        
        const response = await axios.post(`/board/${boardId}/${cmtId}/reaction`, { type });
        console.log('API Response:', response.data);
    } catch (error) {
        console.error('반응 업데이트 오류:', error.response ? error.response.data : error);
        alert('반응을 업데이트하는 중 오류 발생');
    }
};

// 컴포넌트 마운트 시 데이터 로드
onMounted(() => {
    fetchBoardDetails();
});
</script>
