<template>
  <div class="max-w-screen-2xl mx-auto xl:px-20 lg:px-16 md:px-12 sm:px-8 px-6">
    <!-- Loading -->
    <div class="fixed inset-0 h-dvh flex items-center justify-center bg-white bg-opacity-90 z-50" v-if="loading">
      <div class="border-4 border-y-ambassador-blue border-x-inherit border-solid w-10 h-10 rounded-full animate-spin"></div>
    </div>

    <div v-if="updateDetails" class="lg:mt-20 mt-10 grid xl:grid-cols-3 grid-cols-1 xl:gap-x-6 gap-y-8">
      <!-- Main update -->
      <div class="col-span-2 xl:order-1 order-2">
        <div class="relative rounded-t-md border border-solid border-[#F1F3F7] overflow-hidden">
          <img :src="updateDetails.image" class="w-full h-auto object-cover" :alt="updateDetails[`title_${$i18n.locale}`]">
          <div :class="`absolute top-0 end-0 bg-ambassador-blue ${$i18n.locale === 'en' ? 'rounded-tr-md rounded-bl-md' : 'rounded-tl-md rounded-br-md'}`">
            <p class="text-white py-2 px-5 sm:text-base text-sm">
              {{ new Date(updateDetails.created).toLocaleDateString($i18n.locale === 'en' ? 'en-GB' : 'ar-EG', {day: '2-digit', month: 'long', year: 'numeric', numberingSystem: $i18n.locale === 'en' ? 'latn' : 'arab' }) }}
            </p>
          </div>
        </div>
        <div class="xl:mt-8 mt-6">
          <h1 class="font-medium lg:text-3xl sm:text-2xl text-xl text-ambassador-blue">{{ updateDetails[`title_${$i18n.locale}`] }}</h1>
          <p class="xl:mt-5 mt-4 font-light lg:text-lg sm:text-base text-[#737373]" v-html="updateDetails[`content_${$i18n.locale}`] ? updateDetails[`content_${$i18n.locale}`].replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;').replace(/\r?\n/g, '<br>') : ''"></p>
        </div>

        <!-- Pagination -->
        <div class="xl:mt-12 mt-6 flex items-center justify-between gap-4">
          <div v-if="prevUpdate" class="flex items-center lg:gap-4 gap-3">
            <router-link :to="updateHref(prevUpdate)" class="md:w-14 md:h-14 w-10 h-10 border border-[#CCCCCC] hover:border-ambassador-blue rounded-md flex items-center justify-center">
              <span class="material-symbols-rounded text-ambassador-blue font-semibold md:text-2xl text-xl">{{ $i18n.locale === 'en' ? 'arrow_back' : 'arrow_forward' }}</span>
            </router-link>
            <div class="text-start md:block hidden">
              <p class="text-[#737373] text-sm">{{ $t('Previous post') }}</p>
              <p class="mt-1 text-ambassador-blue font-medium md:text-base text-sm">{{ prevUpdate[`title_${$i18n.locale}`] }}</p>
            </div>
          </div>
          <div v-if="nextUpdate" class="flex items-center lg:gap-4 gap-3 ms-auto">
            <div class="text-end md:block hidden">
              <p class="text-[#737373] text-sm">{{ $t('Next post') }}</p>
              <p class="mt-1 text-ambassador-blue font-medium md:text-base text-sm">{{ nextUpdate[`title_${$i18n.locale}`] }}</p>
            </div>
            <router-link :to="updateHref(nextUpdate)" class="md:w-14 md:h-14 w-10 h-10 border border-[#CCCCCC] hover:border-ambassador-blue rounded-md flex items-center justify-center">
              <span class="material-symbols-rounded text-ambassador-blue font-semibold md:text-2xl text-xl">{{ $i18n.locale === 'en' ? 'arrow_forward' : 'arrow_back' }}</span>
            </router-link>
          </div>
        </div>
      </div>

      <!-- Sub Updates -->
      <div class="col-span-1 xl:order-2 order-1 flex flex-col gap-y-6">
        <!-- Search -->
        <!-- <div class="bg-[#F1F3F7] rounded-md p-6">
          <p class="text-ambassador-blue font-medium md:text-2xl sm:text-xl text-lg leading-4">{{ $t('Search') }}</p>
          <div class="flex mt-4">
            <input type="text" name="search" id="search" placeholder="Type here..." class="outline-none px-4 rounded-s-md w-full">
            <button class="bg-ambassador-blue rounded-e-md">
              <span class="material-symbols-rounded text-white w-11 h-11 flex items-center justify-center font-light">search</span>
            </button>
          </div>
        </div> -->

        <!-- Categories -->
        <div class="bg-[#F1F3F7] rounded-md sm:p-6 p-4">
          <p class="text-ambassador-blue font-medium md:text-2xl sm:text-xl text-lg leading-4">{{ $t('Categories') }}</p>
          <div class="flex flex-col sm:gap-3 gap-2 mt-4">
            <div v-for="(category, index) in categories" :key="index">
              <router-link :to="category.updates && category.updates.length > 0 ? updateHref(category.updates[0]) : '#'" :class="`flex items-center justify-between bg-white sm:px-5 px-4 py-3 rounded-[10px] w-full ${category.updates && category.updates.length > 0 ? '' : 'pointer-events-none opacity-60'}`">
                <div class="flex items-center sm:gap-2.5 gap-2">
                  <span class="material-symbols-outlined text-lg font-semibold text-blue-600 leading-6">{{$i18n.locale === 'en' ? 'keyboard_double_arrow_right' : 'keyboard_double_arrow_left'}}</span>
                  <p class="text-ambassador-blue sm:text-lg font-medium leading-6">{{ category[`name_${$i18n.locale}`] }}</p>
                </div>
                <p class="text-xs text-[#737373]">{{ '(' + category.updates?.length + ')' }}</p>
              </router-link>
            </div>
          </div>
        </div>

        <!-- Recent Posts -->
        <div v-if="recentPosts.length > 1" class="bg-[#F1F3F7] rounded-md sm:p-6 p-4">
          <p class="text-ambassador-blue font-medium md:text-2xl sm:text-xl text-lg leading-4">{{ $t('Recent Posts') }}</p>
          <div class="flex flex-col sm:gap-3 gap-2 mt-4">
            <div v-for="(post, index) in recentPosts.filter(item => item.id !== updateDetails.id)" :key="index">
              <div class="bg-white flex rounded-md overflow-hidden">
                <div class="w-24 min-h-24 shrink-0">
                  <img :src="post.image" class="w-full h-full object-cover" :alt="post[`title_${$i18n.locale}`]">
                </div>
                <div class="py-2.5 px-3 w-full h-full">
                  <p class="text-rainmaker text-sm font-light">
                    {{ new Date(post.created).toLocaleDateString($i18n.locale === 'en' ? 'en-GB' : 'ar-EG', {day: '2-digit', month: 'short', year: 'numeric', numberingSystem: $i18n.locale === 'en' ? 'latn' : 'arab'}) }}
                  </p>
                  <router-link :to="updateHref(post)" class="text-ambassador-blue text-base font-medium mt-2 hover:text-blue-600 cursor-pointer">{{ post[`title_${$i18n.locale}`] }}</router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { reactive } from 'vue';
import { useHead } from '@vueuse/head';

export default {
  data () {
    return {
      updateDetails: {},
      categories: [],
      recentPosts: [],
      prevUpdate: {},
      nextUpdate: {},
      loading: false
    }
  },
  setup () {
    const seoState = reactive({
      title: '',
      meta: []
    })

    useHead(seoState)

    return { seoState }
  },
  watch: {
    '$route.params.id' () {
      this.loadUpdateDetails()
    },
    async '$i18n.locale' () {
      await this.goToUpdateDetails()
      this.applySeoFromUpdate()
    } 
  },
  methods: {
    applySeoFromUpdate () {
      const locale = this.$i18n.locale
      const titleValue = this.updateDetails?.[`meta_title_${locale}`] || this.updateDetails?.[`title_${locale}`] || ''
      const descriptionSource = this.updateDetails?.[`meta_description_${locale}`] || this.updateDetails?.[`content_${locale}`] || ''
      const description = descriptionSource
        .replace(/<[^>]*>/g, ' ')
        .replace(/\s+/g, ' ')
        .trim()
        .slice(0, 160)
      const image = this.updateDetails?.image || ''
      const title = titleValue ? `${titleValue} | ValuePlus` : 'ValuePlus'

      if (!titleValue && !description && !image) return

      this.seoState.title = title
      this.seoState.meta = [
        { name: 'description', content: description, key: 'description' },
        { itemprop: 'name', content: title, key: 'itemprop:name' },
        { itemprop: 'description', content: description, key: 'itemprop:description' },
        { itemprop: 'image', content: image, key: 'itemprop:image' },
        { property: 'og:title', content: title, key: 'og:title' },
        { property: 'og:description', content: description, key: 'og:description' },
        { property: 'og:image', content: image, key: 'og:image' },
        { name: 'twitter:title', content: title, key: 'twitter:title' },
        { name: 'twitter:description', content: description, key: 'twitter:description' },
        { name: 'twitter:image', content: image, key: 'twitter:image' }
      ]
    },
    updateHref (updateItem) {
      if (!updateItem) return '#'
      return `/${this.$i18n.locale}/blogs/${updateItem[`slug_${this.$i18n.locale}`]}`
    },
    async loadUpdateDetails () {
      this.loading = true;
      try {
        const response = await axios.get('https://admin.valueerp.net/api/updates');
        const updates = response.data.data.all_updates.data;
        this.categories = response.data.data.categories;

        // find index of current update
        const currentIndex = updates.findIndex(update => [update.slug_en, update.slug_ar].includes(this.$route.params.id));
        
        // current item
        this.updateDetails = updates[currentIndex];
        this.recentPosts = this.categories.find(cat => cat.id === this.updateDetails.category_id)?.updates || [];

        // previous item (if exists)
        this.prevUpdate = currentIndex > 0 ? updates[currentIndex - 1] : null;

        // next item (if exists)
        this.nextUpdate = currentIndex < updates.length - 1 ? updates[currentIndex + 1] : null;

        this.applySeoFromUpdate()
      } catch (error) {
        // this.error = error.message || 'Something went wrong';
      } finally {
        this.loading = false;
      }
    },
    goToUpdateDetails (type) {
      return this.$router.push({
        name: 'blog-details', // 👈 route name
        params: {
          id: 
            type === 'next' ? this.nextUpdate[`slug_${this.$i18n.locale}`] :
            type === 'prev' ? this.prevUpdate[`slug_${this.$i18n.locale}`] :
            this.updateDetails[`slug_${this.$i18n.locale}`]
        }
      }).catch(() => {})
    }
  },
  async serverPrefetch () {
    await this.loadUpdateDetails()
  },
  created () {
    if (typeof window !== 'undefined') {
      this.loadUpdateDetails()
    }
  }
}
</script>
