<template>
  <div class="admin--board-list">
    <!-- 검색 영역 -->
    <div class="admin--search-box">
      <div class="admin--search-form">
        <select v-model="searchType" class="admin--form-select admin--search-select">
          <option value="title">제목</option>
          <option value="name">이름</option>
          <option value="content">내용</option>
        </select>
        <input
          v-model="searchKeyword"
          type="text"
          class="admin--form-input admin--search-input"
          placeholder="검색어를 입력하세요"
          @keyup.enter="handleSearch"
        />
        <button class="admin--btn-small admin--btn-small-primary" @click="handleSearch">
          검색
        </button>
        <button class="admin--btn-small admin--btn-small-secondary" @click="handleReset">
          초기화
        </button>
      </div>
      <div class="admin--search-actions">
        <button class="admin--btn-small admin--btn-small-primary" @click="goToCreate">
          + 등록
        </button>
      </div>
    </div>

    <!-- 테이블 -->
    <div class="admin--table-wrapper">
      <table class="admin--table">
        <thead>
          <tr>
            <th>NO</th>
            <th>제목</th>
            <th>이름</th>
            <th>등록일</th>
            <th>조회</th>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="!posts || posts.length === 0">
            <td colspan="6" class="admin--table-empty">등록된 게시물이 없습니다.</td>
          </tr>
          <tr v-else v-for="(post, index) in posts" :key="post.id">
            <td>
              {{
                (post.is_notice === 1 || post.is_notice === '1')
                  ? "공지"
                  : totalCount - ((currentPage - 1) * perPage + index)
              }}
            </td>
            <td class="admin--table-title">{{ post.title }}</td>
            <td>{{ post.name }}</td>
            <td>{{ formatDate(post.created_at) }}</td>
            <td>{{ post.views }}</td>
            <td>
              <div class="admin--table-actions">
                <button
                  class="admin--btn-small admin--btn-small-primary"
                  @click="goToEdit(post.id)"
                >
                  수정
                </button>
                <button
                  class="admin--btn-small admin--btn-small-danger"
                  @click="handleDelete(post.id)"
                >
                  삭제
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 페이지네이션 -->
    <div v-if="totalPages > 1" class="admin--pagination">
      <button
        class="admin--pagination-btn"
        :disabled="currentPage === 1"
        @click="changePage(1)"
        title="처음"
      >
        ⏮
      </button>
      <button
        class="admin--pagination-btn"
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
        title="이전"
      >
        ◀
      </button>
      <button
        v-for="page in visiblePages"
        :key="page"
        class="admin--pagination-btn"
        :class="{ 'is-active': page === currentPage }"
        @click="changePage(page)"
      >
        {{ page }}
      </button>
      <button
        class="admin--pagination-btn"
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
        title="다음"
      >
        ▶
      </button>
      <button
        class="admin--pagination-btn"
        :disabled="currentPage === totalPages"
        @click="changePage(totalPages)"
        title="끝"
      >
        ⏭
      </button>
    </div>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from "vue";
  import { useRouter } from "vue-router";

  definePageMeta({ layout: "admin", middleware: ["auth"] });

  const router = useRouter();
  const { get, del } = useApi();
  const posts = ref([]);
  const searchType = ref("title");
  const searchKeyword = ref("");
  const currentPage = ref(1);
  const perPage = ref(10);
  const totalCount = ref(0);
  const totalPages = ref(0);

  const visiblePages = computed(() => {
    const pages = [];
    const maxVisible = 5;
    let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2));
    let end = Math.min(totalPages.value, start + maxVisible - 1);
    if (end - start < maxVisible - 1) start = Math.max(1, end - maxVisible + 1);
    for (let i = start; i <= end; i++) pages.push(i);
    return pages;
  });

  const loadPosts = async () => {
    const params = { page: currentPage.value, per_page: perPage.value };
    if (searchKeyword.value) {
      params.search_type = searchType.value;
      params.search_keyword = searchKeyword.value;
    }
    const { data, error } = await get("/board/notice", { params });

    console.log("[NoticeBoard] API 응답:", { data, error });

    // API 응답: { success: true, data: { items, total }, message }
    if (data?.success && data?.data) {
      posts.value = data.data.items || [];
      totalCount.value = data.data.total || 0;
      totalPages.value = Math.ceil(totalCount.value / perPage.value);
      console.log("[NoticeBoard] 로드 성공:", posts.value.length);
    }
  };

  const handleSearch = () => {
    currentPage.value = 1;
    loadPosts();
  };
  const handleReset = () => {
    searchType.value = "title";
    searchKeyword.value = "";
    currentPage.value = 1;
    loadPosts();
  };
  const changePage = (page) => {
    if (page < 1 || page > totalPages.value) return;
    currentPage.value = page;
    loadPosts();
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  const goToCreate = () => router.push("/site-manager/board/notice/create");
  const goToEdit = (id) => router.push(`/site-manager/board/notice/edit/${id}`);
  const handleDelete = async (id) => {
    if (!confirm("정말 삭제하시겠습니까?")) return;
    const { error } = await del(`/board/notice/${id}`);
    if (error) alert("삭제에 실패했습니다.");
    else {
      alert("삭제되었습니다.");
      loadPosts();
    }
  };
  const formatDate = (dateString) => {
    if (!dateString) return "-";
    const date = new Date(dateString);
    return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(
      2,
      "0"
    )}.${String(date.getDate()).padStart(2, "0")}`;
  };

  onMounted(() => loadPosts());
</script>

<style scoped>
  /* 검색 영역 input/select 스타일 통일 */
  .admin--search-box .admin--form-input,
  .admin--search-box .admin--search-input,
  .admin--search-box .admin--form-select,
  .admin--search-box .admin--search-select {
    border: 1px solid var(--admin-border-color) !important;
    border-radius: 4px;
    height: 33px !important;
    padding: 6px 14px !important;
    font-size: 13px !important;
  }
</style>
