<template>
    <div>
      <!-- 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 class="-mt-24 bg-no-repeat bg-cover module-cover pt-48 pb-24 mb-14">
        <div class="max-w-screen-2xl mx-auto xl:px-20 lg:px-16 md:px-12 sm:px-8 px-6">
          <div class="text-white text-center">
            <h1 class="font-bold lg:text-4xl sm:text-3xl text-2xl">{{ sector[`name_${$i18n.locale}`] }}</h1>
          </div>
        </div>
      </div>

      <div class="bg-white sticky z-[2] top-0 mt-5">
        <div class="max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6">
          <div class="flex flex-wrap justify-center py-3">
            <div v-for="(sector, index) in sectorsList" :key="index" :class="`p-3 cursor-pointer border-solid ${[sector.slug_en, sector.slug_ar].includes($route.params.slug) ? 'border-b-2 border-[#122340] text-[#122340]' : 'border-b border-[#82828250] text-[#828282]'}`">
              <router-link :to="`/${$i18n.locale}/sectors/${sector['slug_' + $i18n.locale]}`">{{ sector[`name_${$i18n.locale}`] }}</router-link>
              <!-- <router-link :to="{ path: `/${$i18n.locale}/sectors/${sector['slug_' + $i18n.locale]}` }">{{ sector[`name_${$i18n.locale}`] }}</router-link> -->
            </div>
          </div>
        </div>
      </div>

      <!-- Sector brief -->
      <div class="mt-10 max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6">
        <div class="grid md:grid-cols-3 grid-cols-1 items-center gap-4">
          <div class="md:col-span-2 col-span-1 md:order-1 order-2 text-legal-eagle" v-html="sectorsList.find(sector => [sector.slug_en, sector.slug_ar].includes($route.params.slug))?.[`content_${$i18n.locale}`]"></div>
          <img class="md:order-2 order-1" :src="sectorsList.find(sector => [sector.slug_en, sector.slug_ar].includes($route.params.slug))?.image" :alt="sectorsList.find(sector => [sector.slug_en, sector.slug_ar].includes($route.params.slug))?.[`name_${$i18n.locale}`]">
        </div>
      </div>
  
      <!-- Links -->
      <div class="mt-16 max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6">
        <div class="flex flex-col gap-2">
          <div v-for="(tab, index) in tabs" :key="index">
            <a :href="`#module_${tab.id}`" @click.prevent="scrollToModuleDetails(`module_${tab.id}`)" :class="`w-full md:text-lg cursor-pointer underline hover:text-[#122340]`">
              {{ tab[`name_${$i18n.locale}`] }}
            </a>
          </div>
        </div>
      </div>
  
      <div v-if="modules.length > 0">
        <div v-for="(item, index) in modules" :key="index">
          <modules :id="`module_${item.subCategory_id}`" :modules="[item]" class="pt-20 max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6" />
        </div>
      </div>

      <advantages v-if="advantages.length > 0" :advantageDesc="advantageDesc" :advantages="advantages" class="mt-24 max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6 overflow-x-hidden" />
      <partners v-if="partners.length > 0" :list="partners" title="Partners of Success" class="mt-24 max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6" />
      <testimonials v-if="customersOpinions.length > 0" :customerOpinionDesc="customerOpinionDesc" :customersOpinions="customersOpinions" class="mt-24 max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6" />
      <sector-services v-if="sectorsServices.length > 0" :sectorsServices="sectorsServices" class="mt-24 max-w-screen-2xl mx-auto xl:px-32 lg:px-16 md:px-12 sm:px-8 px-6" />
      <request-offer id="request-offer" :description="description" :contactInfo="contactInfo" :sectorID="sector.id" class="mt-24"/>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { reactive } from 'vue';
  import { useHead } from '@vueuse/head';
  import Modules from '@/components/Modules.vue';
  import Advantages from '@/components/Advantages.vue';
  import Partners from '@/components/Partners.vue';
  import Testimonials from '@/components/Testimonials.vue';
  import RequestOffer from '@/components/RequestOffer.vue';
  import SectorServices from '@/components/SectorServices.vue';
  
  export default {
    data () {
      return {
        sector: {},
        tabs: [],
        partners: [],
        sectorsServices: [],
        customersOpinions: [],
        modules: [],
        advantageDesc: {},
        advantages: [],
        contactInfo: {},
        description: {},
        customerOpinionDesc: {},
        loading: false,
        sectorsList: []
      }
    },
    setup () {
      const seoState = reactive({
        title: '',
        meta: []
      })

      useHead(seoState)

      return { seoState }
    },
    watch: {
      '$route.params.slug' (val) {
        if (![this.sector.slug_en, this.sector.slug_ar].includes(val)) {
          this.loadSector()
        }
      },
      async '$i18n.locale' () {
        await this.$router.push({
          name: 'sectors-details', // 👈 route name
          params: {
            slug: this.sector[`slug_${this.$i18n.locale}`]
          }
        }).catch(() => {})
        this.applySeoFromSector()
      }
    },
    methods: {
      applySeoFromSector () {
        const locale = this.$i18n.locale
        const titleValue = this.sector?.[`meta_title_${locale}`] || this.sector?.[`name_${locale}`] || ''
        const descriptionSource = this.sector?.[`meta_description_${locale}`] || this.sector?.[`content_${locale}`] || ''
        const description = descriptionSource
          .replace(/<[^>]*>/g, ' ')
          .replace(/\s+/g, ' ')
          .trim()
          .slice(0, 160)
        const image = this.sector?.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' }
        ]
      },
      async loadSector () {
        this.loading = true;
        try {
          const response = await axios.get('https://admin.valueerp.net/api/sectorsModules');
          this.sectorsList = response.data.data.data
          this.sector = this.sectorsList.find(element => [element.slug_en, element.slug_ar].includes(this.$route.params.slug));
          this.applySeoFromSector()
          await this.loadSectorDetails()

        } catch (error) {
          // this.error = error.message || 'Something went wrong';
        } finally {
          // this.loading = false;
        }
      },
  
      async loadSectorDetails () {
        try {
          const response = await axios.get(`https://admin.valueerp.net/api/sectorSubcategories?category_id=${this.sector.slug_en}`);
          
          this.tabs = response.data.data.data
          this.partners = response.data.data.partners
          this.customersOpinions = response.data.data.sectors_customers_opinions
          this.modules = response.data.data.sectors_content
          this.advantageDesc = response.data.data.advantage_desc
          this.advantages = response.data.data.sectors_advantages
          this.contactInfo = response.data.data.contact_us_information
          this.description = response.data.data.request_offer_desc
          this.customerOpinionDesc = response.data.data.customer_opinion_desc
          this.sectorsServices = response.data.data.sectors_serves
  
          // Check if the URL contains an anchor link and scroll to the section
          if (typeof window !== 'undefined' && window.location.hash) {
            setTimeout(() => {
              this.scrollToSection(window.location.hash);
            }, 500);
          } else {
            this.loading = false;
          }
        } catch (error) {
          // this.error = error.message || 'Something went wrong';
        } finally {
          this.loading = false;
        }
      },

      scrollToModuleDetails (id) {
        if (typeof document === 'undefined') return
        const element = document.getElementById(id);
        if (element) {
          element.scrollIntoView({
            behavior: 'smooth',
            block: 'start',
          });
        }
      },

      scrollToSection (hash) {    
        if (typeof document === 'undefined') return
        const element = document.querySelector(hash);
        if (element) {
          element.scrollIntoView({
            behavior: 'smooth',
            block: 'start',
          });
        }
      }
    },
    components: {
      Modules,
      Advantages,
      Partners,
      Testimonials,
      RequestOffer,
      SectorServices
    },
    async serverPrefetch () {
      await this.loadSector()
    },
    created () {
      if (typeof window !== 'undefined') {
        this.loadSector()
      }
    }
  }
  </script>
  
  <style lang="scss">
  .module-cover {
    background-image: url('../assets/images/slider-img.svg');
  }
  </style>
