<template>
  <main>
    <TopVisual :className="className" :title="title" :navigation="navigation" />
    <section class="title--section">
      <div class="sub--container type2">
        <div class="title--wrap">
          <h2 class="title">
            그린웨일글로벌은 까다롭기로 유명한 <br />
            <strong>친환경 플라스틱 관련 미국 특허 및 유럽 인증을 획득</strong>하여
            <br />그 기술력을 입증받았습니다.
          </h2>
        </div>
        <div class="tab--wrap patents">
          <a
            @click="filterByCategory('all')"
            :class="{ active: selectedCategory === 'all' }"
            href="javascript:void(0)"
            >전체</a
          >
          <a
            @click="filterByCategory('technology1')"
            :class="{ active: selectedCategory === 'technology1' }"
            href="javascript:void(0)"
            >특허증</a
          >
          <a
            @click="filterByCategory('technology2')"
            :class="{ active: selectedCategory === 'technology2' }"
            href="javascript:void(0)"
            >인증서</a
          >
          <a
            @click="filterByCategory('technology3')"
            :class="{ active: selectedCategory === 'technology3' }"
            href="javascript:void(0)"
            >성적서</a
          >
          <a
            @click="filterByCategory('technology4')"
            :class="{ active: selectedCategory === 'technology4' }"
            href="javascript:void(0)"
            >MSD&TDS</a
          >
        </div>
        <div class="patents--wrap">
          <div class="patents--list">
            <UModal
              v-for="patent in paginatedPatents"
              :key="patent.id"
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal(patent.image)" class="patents">
                <div class="img--wrap">
                  <img :src="patent.image" alt="" />
                </div>
                <h4>{{ patent.title }}</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
            <UModal
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal('/img/top_ban_technology.jpg')" class="patents">
                <div class="img--wrap">
                  <img src="/img/top_ban_technology.jpg" alt="" />
                </div>
                <h4>플라스틱 감축 소재 인증서</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
            <UModal
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal('/img/top_ban_technology.jpg')" class="patents">
                <div class="img--wrap">
                  <img src="/img/top_ban_technology.jpg" alt="" />
                </div>
                <h4>플라스틱 감축 소재 인증서</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
            <UModal
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal('/img/top_ban_technology.jpg')" class="patents">
                <div class="img--wrap">
                  <img src="/img/top_ban_technology.jpg" alt="" />
                </div>
                <h4>플라스틱 감축 소재 인증서</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
            <UModal
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal('/img/top_ban_technology.jpg')" class="patents">
                <div class="img--wrap">
                  <img src="/img/top_ban_technology.jpg" alt="" />
                </div>
                <h4>플라스틱 감축 소재 인증서</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
            <UModal
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal('/img/top_ban_technology.jpg')" class="patents">
                <div class="img--wrap">
                  <img src="/img/top_ban_technology.jpg" alt="" />
                </div>
                <h4>플라스틱 감축 소재 인증서</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
            <UModal
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal('/img/top_ban_technology.jpg')" class="patents">
                <div class="img--wrap">
                  <img src="/img/top_ban_technology.jpg" alt="" />
                </div>
                <h4>플라스틱 감축 소재 인증서</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
            <UModal
              v-model:open="isModalOpen"
              title="특허 / 인증 크게보기"
              :close="false"
            >
              <UButton @click="openModal('/img/top_ban_technology.jpg')" class="patents">
                <div class="img--wrap">
                  <img src="/img/top_ban_technology.jpg" alt="" />
                </div>
                <h4>플라스틱 감축 소재 인증서</h4>
              </UButton>
              <template #content>
                <UButton @click="isModalOpen = false" class="modal--close--btn"></UButton>
                <div class="modal--img--container">
                  <img :src="selectedImage" alt="" />
                </div>
              </template>
            </UModal>
          </div>
          <div class="pagination--wrap">
            <UButton
              @click="prevPage"
              class="prev--btn"
              :disabled="currentPage === 1"
            ></UButton>
            <div class="numbs">
              <UButton
                v-for="page in totalPages"
                :key="page"
                @click="goToPage(page)"
                :class="{ active: currentPage === page }"
              >
                {{ page }}
              </UButton>
            </div>
            <UButton
              @click="nextPage"
              class="next--btn"
              :disabled="currentPage === totalPages"
            ></UButton>
          </div>
        </div>
      </div>
    </section>
  </main>
</template>
<script setup>
  import { ref, computed, onMounted } from "vue";
  import TopVisual from "~/components/topVisual.vue";

  const className = ref("technology");
  const title = ref("Technology");
  const isModalOpen = ref(false);
  const loading = ref(true);
  const patentsData = ref([]);
  const totalCount = ref(0);
  const selectedCategory = ref("all");
  const allPatentsData = ref([]); // 전체 데이터 저장용
  const navigation = ref([
    {
      name: "Technology",
      link: "/technology/patents",
      gnbList: [
        { name: "Company", link: "/company/intro" },
        { name: "Product", link: "/products/materials" },
        { name: "Technology", link: "/technology/facilities" },
        { name: "Media", link: "/media/news" },
        { name: "Contact", link: "/contact/notice" },
      ],
    },
    {
      name: "특허 / 인증",
      link: "/technology/patents",
      gnbList: [
        { name: "시설", link: "/technology/facilities" },
        { name: "특허 / 인증", link: "/technology/patents" },
      ],
    },
  ]);

  const selectedImage = ref("/img/img--patents.png");

  // 전체 데이터 가져오기 (4개 API 합쳐서)
  const fetchAllPatents = async () => {
    try {
      loading.value = true;
      const apis = ["technology1", "technology2", "technology3", "technology4"];
      let allData = [];

      for (const api of apis) {
        const response = await $postForm(`/board_list/${api}`, {
          boardId: api,
          page: 1,
          searchKind: "",
          searchKeyword: "",
        });

        if (response && response.success && response.list) {
          const categoryName = getCategoryName(api);
          const categoryData = response.list.map((item, index) => ({
            id: `${api}_${item.board_idx || index}`,
            title: item.title,
            category: categoryName,
            image: item.main_file1
              ? `http://green.interscope.co.kr/backend${item.main_file1}`
              : "/img/img--patents.png",
          }));
          allData = [...allData, ...categoryData];
        }
      }

      patentsData.value = allData;
      totalCount.value = allData.length;
    } catch (error) {
      console.error("전체 데이터 로드 실패:", error);
      setDefaultPatentsData();
    } finally {
      loading.value = false;
    }
  };

  // 카테고리별 데이터 가져오기
  const fetchPatentsByCategory = async (category) => {
    try {
      loading.value = true;

      const response = await $postForm(`/board_list/${category}`, {
        boardId: category,
        page: 1,
        searchKind: "",
        searchKeyword: "",
      });

      if (response && typeof response === "object") {
        if (response.success && response.list) {
          totalCount.value = response.totalCount || response.list.length;
          const categoryName = getCategoryName(category);

          patentsData.value = response.list.map((item, index) => ({
            id: `${category}_${item.board_idx || index}`,
            title: item.title,
            category: categoryName,
            image: item.main_file1
              ? `http://green.interscope.co.kr/backend${item.main_file1}`
              : "/img/img--patents.png",
          }));
        } else {
          console.error("JSON 응답 형식이 올바르지 않습니다:", response);
          setDefaultPatentsData();
        }
      } else {
        console.error("예상하지 못한 응답 형식:", typeof response, response);
        setDefaultPatentsData();
      }
    } catch (error) {
      console.error("특허/인증 데이터 로드 실패:", error);
      setDefaultPatentsData();
    } finally {
      loading.value = false;
    }
  };

  // 카테고리 이름 맵핑
  const getCategoryName = (apiName) => {
    const categoryMap = {
      technology1: "특허증",
      technology2: "인증서",
      technology3: "성적서",
      technology4: "MSD&TDS",
    };
    return categoryMap[apiName] || "기타";
  };

  // 기본 더미 데이터 설정
  const setDefaultPatentsData = () => {
    patentsData.value = [
      {
        id: 1,
        title: "플라스틱 감축 소재 인증서",
        image: "/img/img--patents.png",
      },
      {
        id: 2,
        title: "플라스틱 감축 소재 인증서",
        image: "/img/top_ban_technology.jpg",
      },
    ];
  };

  // 카테고리별 필터링 함수
  const filterByCategory = async (category) => {
    selectedCategory.value = category;
    currentPage.value = 1;

    if (category === "all") {
      await fetchAllPatents();
    } else {
      await fetchPatentsByCategory(category);
    }
  };

  // 페이지네이션 로직
  const currentPage = ref(1);
  const itemsPerPage = 8;
  const backendPageSize = 20;

  const totalPages = computed(() => Math.ceil(totalCount.value / itemsPerPage));

  const paginatedPatents = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    return patentsData.value.slice(start, end);
  });

  const needToFetchData = (targetPage) => {
    const startIndex = (targetPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage - 1;
    return (
      endIndex >= patentsData.value.length && patentsData.value.length < totalCount.value
    );
  };

  const goToPage = (page) => {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page;
    }
  };

  const nextPage = async () => {
    if (currentPage.value < totalPages.value) {
      await goToPage(currentPage.value + 1);
    }
  };

  const prevPage = async () => {
    if (currentPage.value > 1) {
      await goToPage(currentPage.value - 1);
    }
  };

  const openModal = (imagePath) => {
    selectedImage.value = imagePath;
    isModalOpen.value = true;
  };

  // 컴포넌트 마운트 시 데이터 로드
  onMounted(() => {
    fetchAllPatents(); // 초기에는 전체 데이터 로드
  });
</script>
