// src/components/Calousels.vue
<template>
  <div class="relative w-full overflow-hidden">
    <Carousel
        :autoplay="5000"
        :wrap-around="true"
        :pause-autoplay-on-hover="true"
        :navigation-enabled="true"
        :pagination-enabled="true"
        class="w-full"
    >
      <Slide v-for="(item, i) in items" :key="i">
        <a
            v-if="item.type === 'image'"
            :href="getImageLink(item)"
            :target="item.link || item.File ? '_blank' : '_self'"
            rel="noopener noreferrer"
            class="block w-full carousel__slide-content"
        >
          <img
              :src="`${appStore.imageBaseUrl}${item.image?.url}`"
              alt="Carousel Image"
              class="w-full h-auto object-cover max-h-[600px] sm:max-h-[480px] md:max-h-[550px] lg:max-h-[600px] aspect-video"
          />
        </a>

        <div v-else-if="item.type === 'video' && item.video_url" class="w-full h-full carousel__slide-content">
          <iframe
              :src="getEmbedUrl(item.video_url)"
              frameborder="0"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowfullscreen
              class="w-full h-full object-cover max-h-[600px] sm:max-h-[480px] md:max-h-[550px] lg:max-h-[600px] aspect-video"
          ></iframe>
        </div>

        <div v-else class="w-full h-[300px] bg-gray-200 flex items-center justify-center text-gray-500">
          Content not available
        </div>
      </Slide>

      <template #addons>
        <Navigation />
        <Pagination />
      </template>
    </Carousel>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'; // เพิ่ม watch
import { Carousel, Slide, Pagination, Navigation } from 'vue3-carousel';
import { useAppStore } from '@/stores/app';

const appStore = useAppStore();
const items = ref([]);

const getImageLink = (item) => {
  return item.File?.url ? `${appStore.imageBaseUrl}${item.File.url}` : item.link;
};

const getEmbedUrl = (url) => {
  if (!url) return '';

  const youtubeMatch = url.match(/(?:https?:\/\/)?(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|v\/|)([\w-]{11})(?:\S+)?/);
  if (youtubeMatch && youtubeMatch[1]) {
    return `https://www.youtube.com/embed/${youtubeMatch[1]}?autoplay=1&mute=1&controls=1&showinfo=0&rel=0`;
  }

  const vimeoMatch = url.match(/(?:https?:\/\/)?(?:www\.)?(?:player\.)?vimeo\.com\/(?:video\/)?(\d+)(?:\S+)?/);
  if (vimeoMatch && vimeoMatch[1]) {
    return `https://player.vimeo.com/video/${vimeoMatch[1]}?autoplay=1&muted=1`;
  }

  return url;
};

// --- New function to fetch items ---
const fetchItems = async () => {
  items.value = await appStore.find('calousels');
};

// --- Watch for language changes ---
watch(
    () => appStore.checkLang.isTh, // สิ่งที่เราต้องการ watch คือสถานะภาษา
    async (newLangStatus, oldLangStatus) => {
      // ตรวจสอบว่าภาษามีการเปลี่ยนแปลงจริงหรือไม่
      if (newLangStatus !== oldLangStatus) {
        console.log('Language changed! Fetching new carousel items...');
        await fetchItems(); // เรียก fetchItems อีกครั้ง
      }
    },
    { immediate: true } // ให้เรียก fetchItems() ทันทีเมื่อ component ถูก mount ครั้งแรกด้วย
);

// ลบ onMounted hook เดิมออก ไม่จำเป็นต้องเรียก fetchItems() ซ้ำแล้ว
// onMounted(async () => {
//   items.value = await appStore.find('calousels');
// });
</script>

<style scoped>
/* Optional: Adjust max-height and ensure aspect ratio for video */
.carousel__slide-content {
  display: flex; /* Helps to center content if not full width/height */
  align-items: center;
  justify-content: center;
  height: 100%; /* Ensure content fills the slide height */
  overflow: hidden; /* Prevent overflow if aspect-ratio doesn't fit exactly */
}

/* For aspect-ratio if not supported by browser use padding-bottom trick */
.aspect-video {
  aspect-ratio: 16 / 9; /* Modern way to set aspect ratio */
}

/* Fallback for older browsers if aspect-ratio is not fully supported */
/*
.video-responsive-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; // 16:9 aspect ratio
  height: 0;
  overflow: hidden;
}
.video-responsive-container iframe,
.video-responsive-container video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
*/
</style>