// src/views/info-dissemination/JournalView.vue
<template>
  <div class="container mx-auto px-4 py-8 mb-12">
    <div class="text-center mb-8">
      <h1 class="text-3xl font-bold text-blue-800">
        {{ appStore.isTh ? header : header_en }}
      </h1>
    </div>

    <div class="mb-6 max-w-3xl mx-auto">
      <label class="input input-bordered flex items-center gap-2 shadow-md w-full">
        <input
            type="text"
            class="grow"
            :placeholder="appStore.isTh ? 'ค้นหาวารสาร/ข่าว/นิตยสารด้วยชื่อ...' : 'Search publications by name...'"
            v-model="searchTerm"
        />
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" class="w-4 h-4 opacity-70">
          <path fill-rule="evenodd" d="M9.965 11.023A5.996 5.996 0 0 1 5.996 12C2.686 12 0 9.314 0 5.996 0 2.686 2.686 0 5.996 0c3.308 0 5.996 2.686 5.996 5.996 0 1.544-.582 2.977-1.547 4.027l2.675 2.675c.39.39.39 1.024 0 1.414-.39.39-1.024.39-1.414 0l-2.675-2.675ZM5.996 10.5c2.47 0 4.496-2.026 4.496-4.496S8.466 1.5 5.996 1.5 1.5 3.526 1.5 6.004C1.5 8.47 3.093 10.5 5.996 10.5Z" clip-rule="evenodd" />
        </svg>
      </label>
    </div>

    <div role="tablist" class="tabs tabs-boxed justify-center mb-8 bg-base-200">
      <a
          role="tab"
          class="tab flex-grow sm:flex-none flex flex-col items-center justify-center p-2"
          :class="{ 'tab-active': activeTab === 'all' }"
          @click="activeTab = 'all'"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-8 h-8 mb-1">
          <path stroke-linecap="round" stroke-linejoin="round" d="M10.125 3.75a4.237 4.237 0 0 1 4.375 4.375V12h4.5v6.375a4.237 4.237 0 0 1-4.375 4.375H12c-.621 0-1.125-.504-1.125-1.125v-1.5c0-.621.504-1.125 1.125-1.125h1.5c.621 0 1.125-.504 1.125-1.125V18h4.5a.75.75 0 0 0 .75-.75V12h1.5a.75.75 0 0 0 .75-.75V5.25a.75.75 0 0 0-.75-.75H12a.75.75 0 0 0-.75-.75H6.75a.75.75 0 0 0-.75-.75V3.75c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125Z" />
        </svg>
        {{ appStore.isTh ? 'ทั้งหมด' : 'All' }}
      </a>
      <a
          role="tab"
          class="tab flex-grow sm:flex-none flex flex-col items-center justify-center p-2"
          :class="{ 'tab-active': activeTab === 'journal' }"
          @click="activeTab = 'journal'"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-8 h-8 mb-1">
          <path stroke-linecap="round" stroke-linejoin="round" d="M12 6.042A8.767 8.767 0 0 0 7.5 3H3.375c-.621 0-1.125.504-1.125 1.125v13.5c0 .621.504 1.125 1.125 1.125h4.125c.621 0 1.125-.504 1.125-1.125V15c0-.621.504-1.125 1.125-1.125h3.75c.621 0 1.125.504 1.125 1.125v2.25c0 .621.504 1.125 1.125 1.125h4.125c.621 0 1.125-.504 1.125-1.125V8.25c0-2.25-1.83-4.125-4.08-4.125A8.756 8.756 0 0 0 12 6.042Z" />
        </svg>
        {{ appStore.isTh ? journal_title : journal_title_en }}
      </a>
      <a
          role="tab"
          class="tab flex-grow sm:flex-none flex flex-col items-center justify-center p-2"
          :class="{ 'tab-active': activeTab === 'dailynews' }"
          @click="activeTab = 'dailynews'"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-8 h-8 mb-1">
          <path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5l.75 3.75m-1.5 0L12 7.5M12 7.5V11.25m0-3.75H6.75a2.25 2.25 0 0 0-2.25 2.25v10.5a2.25 2.25 0 0 0 2.25 2.25h10.5a2.25 2.25 0 0 0 2.25-2.25V11.25a2.25 2.25 0 0 0-2.25-2.25H12Z" />
          <path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5L12.75 6H15c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H9.75c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125h2.25Z" />
        </svg>
        {{ appStore.isTh ? news_title : news_title_en }}
      </a>
      <a
          role="tab"
          class="tab flex-grow sm:flex-none flex flex-col items-center justify-center p-2"
          :class="{ 'tab-active': activeTab === 'magazine' }"
          @click="activeTab = 'magazine'"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-8 h-8 mb-1">
          <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.25 22.5H6a2.25 2.25 0 0 1-2.25-2.25V4.5A2.25 2.25 0 0 1 6 2.25h8.25a2.25 2.25 0 0 1 2.25 2.25v1.375a3.375 3.375 0 0 0 3.375 3.375c.573 0 1.127.11 1.647.311a.75.75 0 0 1 .527.712V19.5a2.25 2.25 0 0 1-2.25 2.25h-5.25a2.25 2.25 0 0 1-2.25-2.25Z" />
        </svg>
        {{ appStore.isTh ? magazine_title : magazine_title_en }}
      </a>
    </div>

    <div class="pt-3">
      <div v-if="displayedPublications.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <div
            v-for="(d, i) in displayedPublications"
            :key="d.id"
            class="card bg-base-100 shadow-xl overflow-hidden group relative"
        >
          <figure class="w-full h-48">
            <img
                :src="d.thumbnail.url"
                :alt="appStore.isTh ? d.Title_TH : d.Title_EN"
                class="w-full h-full object-cover"
            />
          </figure>

          <div
              class="absolute inset-0 bg-teal-700 bg-opacity-75 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300"
          >
            <div class="flex space-x-4">
              <button
                  class="btn btn-circle btn-info"
                  @click="openFlipBook(d)"
              >
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-white">
                  <path d="M2.25 18.75a60.076 60.076 0 0 1 1.5-3.004v-7.135C3.75 6.07 4.136 5.5 4.875 5.5H8.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66.54 1.2 1.2 1.2h3.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66.54 1.2 1.2 1.2h3.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66-.54 1.2-1.2 1.2h-3.25c-.66 0-1.2-.54-1.2-1.2v-3.25c0-.66-.54-1.2-1.2-1.2H12c-.66 0-1.2.54-1.2 1.2v3.25c0 .66-.54 1.2-1.2 1.2H4.875c-.739 0-1.125-.57-1.125-1.096v-7.135a60.076 60.076 0 0 1-1.5 3.004ZM4.875 5.5h-.125V3.75c0-.66-.54-1.2-1.2-1.2h-3.25c-.66 0-1.2.54-1.2 1.2v3.25c0 .66.54 1.2 1.2 1.2h3.25c.66 0 1.2-.54 1.2-1.2V5.5ZM12 12c0-.66.54-1.2 1.2-1.2h3.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66-.54 1.2-1.2 1.2h-3.25c-.66 0-1.2-.54-1.2-1.2v-3.25Z" />
                </svg>
              </button>
              <a
                  :href="d.Attachment_TH[0].url"
                  target="_blank"
                  class="btn btn-circle btn-info"
              >
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-white">
                  <path fill-rule="evenodd" d="M11.828 2.25c-.965 0-1.75.785-1.75 1.75v14.5c0 .965.785 1.75 1.75 1.75H18.75c.965 0 1.75-.785 1.75-1.75V8.187c0-.284-.113-.559-.313-.75L15.313 3.107a1.75 1.75 0 0 0-.75-.313H11.828ZM10.5 4a.75.75 0 0 0-.75-.75H6.25A1.75 1.75 0 0 0 4.5 5.75v14.5c0 .965.785 1.75 1.75 1.75h4.25a.75.75 0 0 0 0-1.5H6.25a.25.25 0 0 1-.25-.25V5.75c0-.138.112-.25.25-.25h3.5A.75.75 0 0 0 10.5 4ZM15.75 5.5a.25.25 0 0 1 .25.25v2.25h2.25a.25.25 0 0 1 .25.25v.75H16.25a1.75 1.75 0 0 0-1.75 1.75v3.25c0 .414-.336.75-.75.75H13a.75.75 0 0 0-.75.75v.75c0 .414.336.75.75.75h1.75a.75.75 0 0 0 .75-.75v-.75a.75.75 0 0 0-.75-.75H13a.25.25 0 0 1-.25-.25V10.25c0-.138.112-.25.25-.25h2.25a.75.75 0 0 0 .75-.75V5.75Z" clip-rule="evenodd" />
                </svg>
              </a>
            </div>
          </div>
          <div class="card-body p-4">
            <h6 class="text-base font-semibold text-blue-600">
              {{ appStore.isTh ? d.Title_TH : d.Title_EN }}
            </h6>
            <p class="text-sm text-gray-500">
              {{ appStore.isTh ? `ประเภท: ${getTypeLabel(d.type)}` : `Type: ${getTypeLabel(d.type, 'en')}` }}
            </p>
          </div>
        </div>
      </div>
      <div v-else-if="searchTerm" class="text-center text-gray-500 text-lg mt-8">
        {{ appStore.isTh ? 'ไม่พบเอกสารที่ตรงกับคำค้นหา' : 'No matching publications found.' }}
      </div>
      <div v-else class="text-center text-gray-500 text-lg mt-8">
        {{ appStore.isTh ? 'กำลังโหลดเอกสาร...' : 'Loading publications...' }}
      </div>

      <div v-if="hasMorePublications" class="text-center mt-8">
        <button class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md" @click="loadMorePublications">
          {{ appStore.isTh ? 'โหลดเอกสารเพิ่ม' : 'Load More' }}
        </button>
      </div>
    </div>

    <div
        v-if="overlay"
        class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4"
    >
      <div class="relative w-full h-full max-w-5xl max-h-5xl bg-base-100 rounded-box shadow-2xl">
        <button
            class="btn btn-sm btn-circle btn-error absolute top-4 right-4 z-10"
            @click="overlay = false"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 text-white">
            <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-1.72 6.97a.75.75 0 1 0-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06L12 13.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L13.06 12l1.72-1.72a.75.75 0 1 0-1.06-1.06L12 10.94l-1.72-1.72Z" clip-rule="evenodd" />
          </svg>
        </button>

        <Flipbook ref="flipmain" :pages="currentPages" class="w-full h-full" />

        <div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex space-x-2">
          <button
              class="btn btn-circle btn-sm btn-info"
              @click="flipMainLeft()"
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 text-white">
              <path fill-rule="evenodd" d="M7.72 12.53a.75.75 0 0 1 0-1.06l7.5-7.5a.75.75 0 1 1 1.06 1.06L9.31 12l6.97 6.97a.75.75 0 1 1-1.06 1.06l-7.5-7.5Z" clip-rule="evenodd" />
            </svg>
          </button>
          <button
              class="btn btn-circle btn-sm btn-info"
              @click="flipMainRight()"
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 text-white">
              <path fill-rule="evenodd" d="M16.28 12.28a.75.75 0 0 0 0-1.06l-7.5-7.5a.75.75 0 0 0-1.06 1.06L14.69 12l-6.97 6.97a.75.75 0 1 0 1.06 1.06l7.5-7.5Z" clip-rule="evenodd" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useInfoDisseminationStore } from '@/stores/infoDisseminationStore';
import { useAppStore } from '@/stores/app';

// Constants
const INITIAL_ITEMS = 8; // จำนวนเริ่มต้นที่แสดง, ปรับให้คล้ายกับ PublicationsView
const ITEMS_PER_LOAD = 4; // จำนวนเอกสารที่จะโหลดเพิ่มขึ้นในแต่ละครั้ง

const infoDisseminationStore = useInfoDisseminationStore();
const appStore = useAppStore();

const header = "วารสารองค์กร";
const header_en = "HumanTech Publications";

const journal_title = "สารชาวฮิวแมนเทคไทยแลนด์";
const journal_title_en = "HumanTech Journal";
const news_title = "ข่าวประจำวันฮิวแมนเทคไทยแลนด์";
const news_title_en = "HumanTech Daily News";
const magazine_title = "หนังสือข่าวฮิวแมนเทคไทยแลนด์";
const magazine_title_en = "HumanTech Magazine";

// Reactive States
const activeTab = ref('all');
const allPublications = ref([]); // เก็บข้อมูลทั้งหมดที่ดึงมา
const searchTerm = ref(''); // <--- New: For search functionality
const itemsToShow = ref(INITIAL_ITEMS); // จำนวนรายการที่ต้องการแสดงในปัจจุบัน

const overlay = ref(false);
const currentPages = ref([]);
const flipmain = ref(null);
const isFlipping = ref(false);

// Lifecycle Hook
onMounted(async () => {
  const { journal, dailynews, magazine } = await infoDisseminationStore.fetchPublications();

  allPublications.value = [
    ...journal.map(pub => ({ ...pub, type: 'journal' })),
    ...dailynews.map(pub => ({ ...pub, type: 'dailynews' })),
    ...magazine.map(pub => ({ ...pub, type: 'magazine' }))
  ].sort((a, b) => {
    const dateA = new Date(a.createdAt);
    const dateB = new Date(b.createdAt);
    return dateB - dateA;
  });
});

// Computed Properties
const filteredPublications = computed(() => {
  let publications = allPublications.value;

  // Filter by tab
  if (activeTab.value !== 'all') {
    publications = publications.filter(pub => pub.type === activeTab.value);
  }

  // Filter by search term
  if (searchTerm.value) {
    const lowerCaseSearchTerm = searchTerm.value.toLowerCase();
    publications = publications.filter(pub =>
        (pub.Title_TH && pub.Title_TH.toLowerCase().includes(lowerCaseSearchTerm)) ||
        (pub.Title_EN && pub.Title_EN.toLowerCase().includes(lowerCaseSearchTerm))
    );
  }
  return publications;
});

const displayedPublications = computed(() => {
  return filteredPublications.value.slice(0, itemsToShow.value);
});

const hasMorePublications = computed(() => {
  return itemsToShow.value < filteredPublications.value.length;
});

// Watcher เพื่อรีเซ็ต itemsToShow เมื่อเปลี่ยน Tab หรือคำค้นหาเปลี่ยน
watch(activeTab, () => {
  itemsToShow.value = INITIAL_ITEMS; // รีเซ็ตเมื่อเปลี่ยนแท็บ
});

watch(searchTerm, () => {
  itemsToShow.value = INITIAL_ITEMS; // <--- New: รีเซ็ตเมื่อคำค้นหาเปลี่ยน
});

// Methods
const loadMorePublications = () => {
  itemsToShow.value += ITEMS_PER_LOAD;
};

const openFlipBook = (publication) => {
  currentPages.value = publication.images.map(img => img.url);
  overlay.value = true;
};

const flipMainLeft = () => {
  if (flipmain.value && !isFlipping.value && flipmain.value.currentPage > 0) {
    isFlipping.value = true;
    flipmain.value.flipLeft();
    setTimeout(() => {
      isFlipping.value = false;
    }, 700);
  }
};

const flipMainRight = () => {
  if (flipmain.value && !isFlipping.value && flipmain.value.currentPage < flipmain.value.numPages) {
    isFlipping.value = true;
    flipmain.value.flipRight();
    setTimeout(() => {
      isFlipping.value = false;
    }, 700);
  }
};

const getTypeLabel = (type, lang) => {
  const currentLang = appStore.isTh ? 'th' : 'en';
  const useLang = lang || currentLang;

  if (useLang === 'th') {
    if (type === 'journal') return journal_title;
    if (type === 'dailynews') return news_title;
    if (type === 'magazine') return magazine_title;
  } else {
    if (type === 'journal') return journal_title_en;
    if (type === 'dailynews') return news_title_en;
    if (type === 'magazine') return magazine_title_en;
  }
  return '';
};
</script>

<style scoped>
.flipbook {
  width: 90vw;
  height: 90vh;
  max-width: 100%;
  max-height: 100%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>