// src/views/info-dissemination/MultimediaGallery.vue
<template>
  <div class="container mx-auto px-4 md:px-8 lg:px-16 py-12 bg-white shadow-lg rounded-lg mb-12">

    <div class="text-center mb-8">
      <h1 class="text-3xl font-bold text-blue-800">
        {{ appStore.checkLang.isTh ? title : title_en }}
      </h1>
      <p class="mt-2 text-lg text-gray-700">
        {{ appStore.checkLang.isTh ? 'คลังภาพ วิดีโอ และเสียงขององค์กร' : 'HumanTech Photo, Video, and Audio Archive' }}
      </p>
    </div>

    <div class="mb-8 flex justify-center"> <div class="relative w-full max-w-md px-4"> <input
        type="text"
        v-model="searchTerm"
        :placeholder="appStore.checkLang.isTh ? 'ค้นหาสื่อ (เช่น ชื่อวิดีโอ, รูปภาพ, เสียง)' : 'Search media (e.g., video, photo, audio name)'"
        class="input input-bordered w-full pr-10 pl-4 py-2 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
    />
      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 absolute right-7 top-1/2 -translate-y-1/2 text-gray-400"> <path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
      </svg>
    </div>
    </div>


    <div role="tablist" class="tabs tabs-boxed justify-center mb-8 bg-gray-100 p-2 rounded-lg shadow-md">
      <a
          role="tab"
          class="tab flex-grow sm:flex-none flex flex-col items-center justify-center p-3 text-blue-700 font-medium transition-all duration-200"
          :class="{ 'tab-active bg-blue-600 text-white shadow-lg': activeTab === 'videos' }"
          @click="changeTab('videos')"
      >
        <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="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z" />
        </svg>
        {{ appStore.checkLang.isTh ? vdo : vdo_en }}
      </a>
      <a
          role="tab"
          class="tab flex-grow sm:flex-none flex flex-col items-center justify-center p-3 text-green-700 font-medium transition-all duration-200"
          :class="{ 'tab-active bg-green-600 text-white shadow-lg': activeTab === 'photos' }"
          @click="changeTab('photos')"
      >
        <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="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18.283 2.724a.75.75 0 0 1-.724-.724V6.75a2.25 2.25 0 0 1 2.25-2.25h10.5a2.25 2.25 0 0 1 2.25 2.25v7.21l-3.007 3.007a.75.75 0 0 1-.724.724H3.375Z" />
          <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 6.75h.008v.008H6.75V6.75Z" />
        </svg>
        {{ appStore.checkLang.isTh ? photo : photo_en }}
      </a>
      <a
          role="tab"
          class="tab flex-grow sm:flex-none flex flex-col items-center justify-center p-3 text-purple-700 font-medium transition-all duration-200"
          :class="{ 'tab-active bg-purple-600 text-white shadow-lg': activeTab === 'audio' }"
          @click="changeTab('audio')"
      >
        <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.114 5.666a.75.75 0 0 1 .158 1.09L13.13 12l6.143 5.242a.75.75 0 0 1-.158 1.09l-11.52-9.83a.75.75 0 0 1 0-1.09l11.52-9.83ZM10.51 12H3.75" />
        </svg>
        {{ appStore.checkLang.isTh ? audio_label : audio_label_en }}
      </a>
    </div>

    <div class="tab-content pt-3">
      <p class="mb-4 text-sm text-gray-500">Active Tab: <span class="font-bold text-gray-700">{{ activeTab }}</span></p>

      <div v-if="activeTab === 'videos'" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
            v-for="video in displayedVideos"
            :key="video.id"
            class="card w-full bg-base-100 shadow-xl hover:shadow-2xl transition-shadow duration-300"
        >
          <figure class="h-48 overflow-hidden bg-gray-200">
            <img :src="video.thumb || ''" :alt="video.title" class="w-full h-full object-cover" />
          </figure>
          <div class="card-body p-4">
            <h2 class="card-title text-lg font-bold text-gray-800 line-clamp-2">{{ appStore.checkLang.isTh ? video.title : video.title_en }}</h2>
            <div class="card-actions justify-end mt-2">
              <button class="btn btn-primary btn-sm" @click="openVideoModal(video.embedUrl)">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 mr-1">
                  <path fill-rule="evenodd" d="M4.5 5.653c0-1.427 1.529-2.32 2.75-1.629l11.5 6.709c1.221.712 1.221 2.525 0 3.237l-11.5 6.709c-1.221.72-2.75-.173-2.75-1.629V5.653Z" clip-rule="evenodd" />
                </svg>
                {{ appStore.checkLang.isTh ? playVideoText : playVideoText_en }}
              </button>
            </div>
          </div>
        </div>
        <div v-if="displayedVideos.length === 0 && searchTerm" class="col-span-full text-center text-gray-500 mt-6">
          {{ appStore.checkLang.isTh ? 'ไม่พบวิดีโอที่ตรงกับการค้นหา' : 'No videos found matching your search.' }}
        </div>
        <div v-if="hasMoreVideos" class="col-span-full flex justify-center mt-6">
          <button class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md" @click="loadMoreVideos">
            {{ appStore.checkLang.isTh ? loadMoreVideosText : loadMoreVideosText_en }}
          </button>
        </div>
      </div>

      <div v-if="activeTab === 'photos'" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
            v-for="gallery in displayedGalleries"
            :key="gallery.id"
            class="card w-full bg-base-100 shadow-xl hover:shadow-2xl transition-shadow duration-300"
        >
          <figure class="h-48 overflow-hidden bg-gray-200">
            <img :src="gallery.images[0]?.url || ''" :alt="gallery.name" class="w-full h-full object-cover" />
          </figure>
          <div class="card-body p-4">
            <h2 class="card-title text-lg font-bold text-gray-800 line-clamp-2">{{ appStore.checkLang.isTh ? gallery.name : gallery.name_en }}</h2>
            <div class="card-actions justify-end mt-2">
              <button class="btn btn-secondary btn-sm" @click="openImageModal(gallery.images[0]?.url)">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 mr-1">
                  <path fill-rule="evenodd" d="M1.5 6a2.25 2.25 0 0 1 2.25-2.25h16.5A2.25 2.25 0 0 1 22.5 6v12a2.25 2.25 0 0 1-2.25 2.25H3.75A2.25 2.25 0 0 1 1.5 18V6ZM3 16.06V18c0 .414.336.75.75.75h16.5A.75.75 0 0 0 21 18v-1.94l-2.69-2.689a1.5 1.5 0 0 0-2.12 0L9.47 16.061l-2.689-2.69a1.5 1.5 0 0 0-2.12 0L3 16.061ZM16.5 7.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z" clip-rule="evenodd" />
                </svg>
                {{ appStore.checkLang.isTh ? viewPhotosText : viewPhotosText_en }}
              </button>
            </div>
          </div>
        </div>
        <div v-if="displayedGalleries.length === 0 && searchTerm" class="col-span-full text-center text-gray-500 mt-6">
          {{ appStore.checkLang.isTh ? 'ไม่พบรูปภาพที่ตรงกับการค้นหา' : 'No photos found matching your search.' }}
        </div>
        <div v-if="hasMoreGalleries" class="col-span-full flex justify-center mt-6">
          <button class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md" @click="loadMoreGalleries">
            {{ appStore.checkLang.isTh ? loadMorePhotosText : loadMorePhotosText_en }}
          </button>
        </div>
      </div>

      <div v-if="activeTab === 'audio'" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
            v-for="audioItem in displayedAudio"
            :key="audioItem.id"
            class="card w-full bg-base-100 shadow-xl hover:shadow-2xl transition-shadow duration-300"
        >
          <figure class="h-48 overflow-hidden bg-gray-200">
            <img :src="audioItem.thumbnail || ''" :alt="audioItem.title" class="w-full h-full object-cover" />
          </figure>
          <div class="card-body p-4">
            <h2 class="card-title text-lg font-bold text-gray-800 line-clamp-2">{{ appStore.checkLang.isTh ? audioItem.title : audioItem.title_en }}</h2>
            <audio controls class="w-full mt-2">
              <source :src="audioItem.file" type="audio/mpeg">
              Your browser does not support the audio element.
            </audio>
          </div>
        </div>
        <div v-if="displayedAudio.length === 0 && searchTerm" class="col-span-full text-center text-gray-500 mt-6">
          {{ appStore.checkLang.isTh ? 'ไม่พบไฟล์เสียงที่ตรงกับการค้นหา' : 'No audio files found matching your search.' }}
        </div>
        <div v-if="hasMoreAudio" class="col-span-full flex justify-center mt-6">
          <button class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md" @click="loadMoreAudio">
            {{ appStore.checkLang.isTh ? loadMoreAudioText : loadMoreAudioText_en }}
          </button>
        </div>
      </div>
    </div>

    <dialog id="video_modal" class="modal">
      <div class="modal-box w-11/12 max-w-5xl">
        <form method="dialog">
          <button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2" @click.prevent="closeVideoModal">✕</button>
        </form>
        <h3 class="font-bold text-lg mb-4">
          {{ appStore.checkLang.isTh ? 'วิดีโอ' : 'Video' }}
        </h3>
        <div class="aspect-video w-full">
          <iframe
              v-if="currentVideoUrl"
              :src="currentVideoUrl"
              title="YouTube video player"
              frameborder="0"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowfullscreen
              class="w-full h-full"
          ></iframe>
          <div v-else class="flex items-center justify-center h-full text-gray-500">
            {{ appStore.checkLang.isTh ? 'ไม่มีวิดีโอที่เลือก' : 'No video selected.' }}
          </div>
        </div>
      </div>
    </dialog>

    <dialog id="image_modal" class="modal">
      <div class="modal-box w-11/12 max-w-xl p-6">
        <h3 class="font-bold text-xl mb-4 text-green-700">{{ appStore.checkLang.isTh ? 'ดูรูปภาพ' : 'Image View' }}</h3>
        <div class="flex justify-center items-center h-auto max-h-[80vh] overflow-hidden bg-gray-200 rounded-lg">
          <img :src="currentImageUrl || ''" alt="Enlarged Image" class="max-w-full max-h-[75vh] object-contain rounded-lg" />
        </div>
        <div class="modal-action mt-6">
          <form method="dialog">
            <button class="btn btn-error" @click="closeImageModal">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
              </svg>
              {{ appStore.checkLang.isTh ? 'ปิด' : 'Close' }}
            </button>
          </form>
        </div>
      </div>
    </dialog>

  </div>
</template>

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

// Initialize Pinia stores
const appStore = useAppStore();
const infoDisseminationStore = useInfoDisseminationStore();
const router = useRouter();

// Reactive variables for component state
const activeTab = ref('videos');
const currentVideoUrl = ref('');
const currentImageUrl = ref('');
const searchTerm = ref(''); // New: Reactive variable for search term

// --- New reactive variables for load more functionality ---
const videosToShow = ref(6);
const galleriesToShow = ref(6);
const audioToShow = ref(6);
const itemsPerPage = 3; // Number of items to load each time

// Static text content (for Titles and Tabs)
const photo = "คลังภาพ";
const photo_en = "Photo Gallery";
const vdo = "คลังวีดีโอ";
const vdo_en = "Video Gallery";
const audio_label = "คลังเสียง";
const audio_label_en = "Audio Gallery";
const title = "คลังสื่อ: ภาพ วิดีโอ และเสียง";
const title_en = "Media Archive: Photos, Videos, and Audio";

// --- Static text content for Buttons (now multi-language) ---
const playVideoText = "เล่นวิดีโอ";
const playVideoText_en = "Play Video";
const viewPhotosText = "ดูรูปภาพ";
const viewPhotosText_en = "View Photos";
const loadMoreVideosText = "โหลดวิดีโอเพิ่ม";
const loadMoreVideosText_en = "Load More Videos";
const loadMorePhotosText = "โหลดรูปภาพเพิ่ม";
const loadMorePhotosText_en = "Load More Photos";
const loadMoreAudioText = "โหลดเสียงเพิ่ม";
const loadMoreAudioText_en = "Load More Audio";
const noVideoSelectedText = "ไม่มีวิดีโอที่เลือก";
const noVideoSelectedText_en = "No video selected.";
const closeButtonText = "ปิด";
const closeButtonText_en = "Close";


// Fetch all necessary data on component mount
onMounted(() => {
  infoDisseminationStore.fetchVideos();
  infoDisseminationStore.fetchGalleries();
  infoDisseminationStore.fetchAudio();
});

// --- New computed properties for filtered items ---
const filteredVideos = computed(() => {
  if (!searchTerm.value) {
    return infoDisseminationStore.getVideosForDisplay;
  }
  const lowerCaseSearchTerm = searchTerm.value.toLowerCase();
  return infoDisseminationStore.getVideosForDisplay.filter(video => {
    const titleMatch = video.title?.toLowerCase().includes(lowerCaseSearchTerm);
    const titleEnMatch = video.title_en?.toLowerCase().includes(lowerCaseSearchTerm);
    return titleMatch || titleEnMatch;
  });
});

const filteredGalleries = computed(() => {
  if (!searchTerm.value) {
    return infoDisseminationStore.getGalleriesForDisplay;
  }
  const lowerCaseSearchTerm = searchTerm.value.toLowerCase();
  return infoDisseminationStore.getGalleriesForDisplay.filter(gallery => {
    const nameMatch = gallery.name?.toLowerCase().includes(lowerCaseSearchTerm);
    const nameEnMatch = gallery.name_en?.toLowerCase().includes(lowerCaseSearchTerm);
    return nameMatch || nameEnMatch;
  });
});

const filteredAudio = computed(() => {
  if (!searchTerm.value) {
    return infoDisseminationStore.getAudioForDisplay;
  }
  const lowerCaseSearchTerm = searchTerm.value.toLowerCase();
  return infoDisseminationStore.getAudioForDisplay.filter(audioItem => {
    const titleMatch = audioItem.title?.toLowerCase().includes(lowerCaseSearchTerm);
    const titleEnMatch = audioItem.title_en?.toLowerCase().includes(lowerCaseSearchTerm);
    return titleMatch || titleEnMatch;
  });
});

// --- Updated computed properties for displayed items (using filtered data) ---
const displayedVideos = computed(() => {
  return filteredVideos.value.slice(0, videosToShow.value);
});

const displayedGalleries = computed(() => {
  return filteredGalleries.value.slice(0, galleriesToShow.value);
});

const displayedAudio = computed(() => {
  return filteredAudio.value.slice(0, audioToShow.value);
});

// --- Updated computed properties to check if there are more items to load (using filtered data) ---
const hasMoreVideos = computed(() => {
  return videosToShow.value < filteredVideos.value.length;
});

const hasMoreGalleries = computed(() => {
  return galleriesToShow.value < filteredGalleries.value.length;
});

const hasMoreAudio = computed(() => {
  return audioToShow.value < filteredAudio.value.length;
});

// --- Methods for loading more items ---
const loadMoreVideos = () => {
  videosToShow.value += itemsPerPage;
};

const loadMoreGalleries = () => {
  galleriesToShow.value += itemsPerPage;
};

const loadMoreAudio = () => {
  audioToShow.value += itemsPerPage;
};

// --- Method to reset item counts when changing tabs and also clear search term ---
const changeTab = (tabName) => {
  activeTab.value = tabName;
  searchTerm.value = ''; // Clear search term when changing tabs
  // Reset counts when switching tabs to show initial 6 items for the new tab
  videosToShow.value = 6;
  galleriesToShow.value = 6;
  audioToShow.value = 6;
};

// --- Watch for changes in searchTerm to reset display counts ---
watch(searchTerm, () => {
  videosToShow.value = 6;
  galleriesToShow.value = 6;
  audioToShow.value = 6;
});


// Watchers for debugging (keep these for now, can remove in production)
watch(
    () => infoDisseminationStore.getVideosForDisplay,
    (newVideos) => {
      if (newVideos && newVideos.length > 0) {
        console.log('Watch: ข้อมูลวิดีโอพร้อมแสดงผลแล้ว:', newVideos);
      }
    },
    { deep: true, immediate: true }
);

watch(
    () => infoDisseminationStore.getGalleriesForDisplay,
    (newGalleries) => {
      if (newGalleries && newGalleries.length > 0) {
        console.log('Watch: ข้อมูลแกลเลอรี่พร้อมแสดงผลแล้ว:', newGalleries);
      }
    },
    { deep: true, immediate: true }
);

watch(
    () => infoDisseminationStore.getAudioForDisplay,
    (newAudio) => {
      if (newAudio && newAudio.length > 0) {
        console.log('Watch: ข้อมูลเสียงพร้อมแสดงผลแล้ว:', newAudio);
      }
    },
    { deep: true, immediate: true }
);

// Video Modal functions
const openVideoModal = (url) => {
  console.log("URL ที่ได้รับใน openVideoModal (จาก Store):", url);
  if (url) {
    currentVideoUrl.value = url;
    document.getElementById('video_modal').showModal();
  } else {
    console.error("ไม่ได้รับ URL วิดีโอที่ถูกต้องจากปุ่ม Play.");
  }
};

const closeVideoModal = () => {
  currentVideoUrl.value = '';
  const modal = document.getElementById('video_modal');
  if (modal) modal.close();
};

// Image Modal functions
const openImageModal = (url) => {
  console.log("Opening image modal with URL:", url);
  currentImageUrl.value = url;
  document.getElementById('image_modal').showModal();
};

const closeImageModal = () => {
  currentImageUrl.value = '';
  document.getElementById('image_modal').close();
};
</script>

<style scoped>
.tab-content {
  display: block !important;
}
</style>