<template>
  <Content
    v-if="!empty"
    ref="contentRef"
    wrapper-class="am-fcip"
    form-class="am-fcip__form"
    heading-class="am-fcip__header"
    :content-class="`am-fcip__content ${scrollVisibility ? '' : 'no-scroll'}`"
    :style="cssVars"
  >
    <template v-if="backBtnVisibility" #header>
      <Header
        :btn-string="amLabels.back_btn"
        :btn-type="customizedOptions.backBtn.buttonType"
        role="navigation"
        :aria-label="amLabels.back_btn"
        @go-back="goBack"
      ></Header>
    </template>
    <template #heading>
      <div
        :class="[{ 'am-tablet': pageWidth <= 678 }, { 'am-mobile': pageWidth < 450 }]"
        class="am-fcip__header-top"
        role="region"
        aria-label="Package Information"
      >
        <div class="am-fcip__header-text">
          <span class="am-fcip__header-name" role="heading" aria-level="1">
            <span>
              {{ pack.name }}
            </span>
          </span>
          <div v-if="customizedOptions.packageBadge.visibility" class="am-fcip__badge am-package">
            <span class="am-icon-shipment" aria-hidden="true"></span>
            <span>
              {{ amLabels.package }}
            </span>
          </div>
        </div>
        <div class="am-fcip__header-action">
          <span
            v-if="pack.discount && customizedOptions.packagePrice.visibility"
            class="am-fcip__header-discount"
          >
            {{ `${amLabels.save} ${pack.discount}%` }}
          </span>
          <span v-if="customizedOptions.packagePrice.visibility" class="am-fcip__header-price">
            {{ pack.price ? useFormattedPrice(usePackageAmount(pack)) : amLabels.free }}
          </span>
          <span
            v-if="
              pack.price &&
              (customizedOptions.tax?.visibility ?? true) &&
              useTaxVisibility(store, pack.id, 'package')
            "
            class="am-fcip__header-tax"
          >
            <template v-if="amSettings.payments.taxes.excluded">
              {{ `+${amLabels.total_tax_colon}` }}
            </template>
            <template v-else>
              {{ amLabels.incl_tax }}
            </template>
          </span>
          <span class="am-fcip__header-btn">
            <AmButton :type="customizedOptions.bookingBtn.buttonType" @click="bookNow">
              {{ amLabels.book_now }}
            </AmButton>
          </span>
        </div>
      </div>
      <div
        v-if="
          (customizedOptions.packageCategory.visibility && preselected.package.length !== 1) ||
          customizedOptions.packageDuration.visibility ||
          customizedOptions.packageCapacity.visibility ||
          (customizedOptions.packageLocation.visibility && packLocations.length)
        "
        class="am-fcip__header-bottom"
      >
        <div class="am-fcip__mini-info">
          <div v-if="catNameVisibility" class="am-fcip__mini-info__inner">
            <span class="am-icon-folder" aria-hidden="true"></span>
            <span>{{ category.name }}</span>
          </div>
          <div
            v-if="customizedOptions.packageDuration.visibility"
            class="am-fcip__mini-info__inner"
          >
            <span class="am-icon-clock" aria-hidden="true"></span>
            <span v-if="pack.endDate">
              {{ `${amLabels.expires_at} ${pack.endDate.split(' ')[0]}` }}
            </span>
            <span v-else-if="pack.durationCount">
              {{
                `${amLabels.expires_after} ${pack.durationCount} ${packageDurationLabel(
                  pack.durationCount,
                  pack.durationType,
                )}`
              }}
            </span>
            <span v-else>
              {{ amLabels.without_expiration }}
            </span>
          </div>
          <div
            v-if="customizedOptions.packageCapacity.visibility"
            class="am-fcip__mini-info__inner"
          >
            <span class="am-icon-user" aria-hidden="true"></span>
            <span>1/1</span>
          </div>
          <div
            v-if="packLocations.length && customizedOptions.packageLocation.visibility"
            class="am-fcip__mini-info__inner"
          >
            <span class="am-icon-locations" aria-hidden="true"></span>
            <span>
              {{ displayPackageLocationLabel(packLocations) }}
            </span>
          </div>
        </div>
      </div>
    </template>
    <template #content>
      <!-- Package Gallery -->
      <div v-if="pack.gallery.length" class="am-fcip__gallery">
        <div
          class="am-fcip__gallery-hero"
          :class="[{ w100: pack.gallery.length === 1 }, { 'am-mobile w100': pageWidth < 678 }]"
          :style="{
            backgroundImage: `url(${pack.gallery[0].pictureFullPath})`,
          }"
          role="button"
          tabindex="0"
          aria-haspopup="dialog"
          :aria-label="getGalleryImageLabel(0)"
          @click="openGallery(0)"
          @keydown.enter="openGallery(0)"
          @keydown.space.prevent="openGallery(0)"
        ></div>
        <div
          v-if="packageThumbsGallery.length && pageWidth > 677"
          class="am-fcip__gallery-thumb__wrapper"
        >
          <div
            v-for="(img, index) in packageThumbsGallery"
            :key="index"
            class="am-fcip__gallery-thumb"
            :class="{ 'am-one-thumb': packageThumbsGallery.length === 1 }"
            :style="{ backgroundImage: `url(${img.pictureFullPath})` }"
            role="button"
            tabindex="0"
            aria-haspopup="dialog"
            :aria-label="getGalleryImageLabel(index + 1)"
            @click="openGallery(index + 1)"
            @keydown.enter="openGallery(index + 1)"
            @keydown.space.prevent="openGallery(index + 1)"
          ></div>
        </div>
        <AmButton
          v-if="pack.gallery.length > 1"
          :custom-class="`am-fcip__gallery-btn${pageWidth < 678 ? ' am-mobile' : ''}`"
          category="secondary"
          type="filled"
          @click="openGallery(0)"
        >
          <span class="am-icon-gallery" aria-hidden="true"></span>
          <span>
            {{ amLabels.view_all_photos }}
          </span>
        </AmButton>
      </div>
      <!-- Service Gallery -->

      <!-- Gallery Images -->
      <AmDialog
        v-model="galleryDialog"
        :modal-class="'amelia-v2-booking amelia-v2-gdp'"
        :append-to-body="true"
        :center="true"
        :lock-scroll="false"
        width="768px"
      >
        <div class="am-gd" :style="cssGalleryDialogVars">
          <div class="am-gd__display-wrapper">
            <div class="am-gd__arrows" style="display: flex; justify-content: space-between">
              <span
                class="am-icon-arrow-left"
                role="button"
                tabindex="0"
                :aria-label="amLabels.previous_image || 'Previous image'"
                @click="previousGalleryImage"
                @keydown.enter="previousGalleryImage"
                @keydown.space.prevent="previousGalleryImage"
              ></span>
              <span
                class="am-icon-arrow-right"
                role="button"
                tabindex="0"
                :aria-label="amLabels.next_image || 'Next image'"
                @click="nextGalleryImage"
                @keydown.enter="nextGalleryImage"
                @keydown.space.prevent="nextGalleryImage"
              ></span>
            </div>
            <div
              v-for="(img, index) in pack.gallery"
              :key="index"
              class="am-gd__display"
              :style="{ display: index === activeImage ? 'flex' : 'none' }"
              role="button"
              :tabindex="index === activeImage ? 0 : -1"
              :aria-label="`${amLabels.next_image || 'Next image'}: ${getGalleryImageAlt(index)}`"
              @click="nextGalleryImage"
              @keydown.enter="nextGalleryImage"
              @keydown.space.prevent="nextGalleryImage"
            >
              <img :src="img.pictureFullPath" :alt="getGalleryImageAlt(index)" />
            </div>
          </div>
          <div class="am-gd__selection" aria-live="polite">
            {{ `${activeImage + 1}/${pack.gallery.length}` }}
          </div>
          <div
            class="am-gd__thumb-wrapper"
            role="listbox"
            :aria-label="amLabels.view_all_photos || 'Package gallery'"
          >
            <div
              v-for="(img, index) in pack.gallery"
              :key="index"
              :id="`am-fcip-gallery-thumb-${index}`"
              class="am-gd__thumb"
              :class="{ 'am-active': index === activeImage }"
              :style="{ backgroundImage: `url(${img.pictureFullPath})` }"
              role="option"
              :tabindex="index === activeImage ? 0 : -1"
              :aria-selected="index === activeImage"
              :aria-label="getGalleryImageLabel(index)"
              @click="setActiveGalleryImage(index)"
              @keydown.enter="setActiveGalleryImage(index)"
              @keydown.space.prevent="setActiveGalleryImage(index)"
              @keydown.left.prevent="selectPreviousGalleryThumb"
              @keydown.right.prevent="selectNextGalleryThumb"
            ></div>
          </div>
        </div>
      </AmDialog>
      <!-- /Gallery Images -->

      <!-- Package Info - (description, employees) -->
      <div
        v-if="
          (customizedOptions.packageDescription.visibility &&
            useDescriptionVisibility(pack.description)) ||
          customizedOptions.packageEmployees.visibility
        "
        class="am-fcip__info"
      >
        <div
          class="am-fcip__info-tab__wrapper"
          role="tablist"
          :aria-label="amLabels.package || 'Package details'"
        >
          <div
            v-if="
              useDescriptionVisibility(pack.description) &&
              customizedOptions.packageDescription.visibility
            "
            class="am-fcip__info-tab"
            :class="{ 'am-active': tabsActive === 'description' }"
            id="am-fcip-description-tab"
            role="tab"
            :tabindex="tabsActive === 'description' ? 0 : -1"
            :aria-selected="tabsActive === 'description'"
            aria-controls="am-fcip-description-panel"
            @click="setActiveInfoTab('description')"
            @keydown="handleInfoTabKeydown($event, 'description')"
          >
            {{ amLabels.about_package }}
          </div>
          <div
            v-if="customizedOptions.packageEmployees.visibility"
            :class="{ 'am-active': tabsActive === 'employees' }"
            class="am-fcip__info-tab"
            id="am-fcip-employees-tab"
            role="tab"
            :tabindex="tabsActive === 'employees' ? 0 : -1"
            :aria-selected="tabsActive === 'employees'"
            aria-controls="am-fcip-employees-panel"
            @click="setActiveInfoTab('employees')"
            @keydown="handleInfoTabKeydown($event, 'employees')"
          >
            {{ amLabels.tab_employees }}
          </div>
        </div>
        <div class="am-fcip__info-content__wrapper">
          <!-- Description -->
          <div
            v-if="
              useDescriptionVisibility(pack.description) &&
              customizedOptions.packageDescription.visibility
            "
            v-show="tabsActive === 'description'"
            class="am-fcip__info-content"
            id="am-fcip-description-panel"
            role="tabpanel"
            aria-labelledby="am-fcip-description-tab"
            tabindex="0"
          >
            <div class="am-fcip__info-service__desc ql-description" v-html="pack.description"></div>
          </div>
          <!-- /Description -->

          <!-- Employees -->
          <div
            v-if="customizedOptions.packageEmployees.visibility"
            v-show="tabsActive === 'employees'"
            class="am-fcip__info-content"
            id="am-fcip-employees-panel"
            role="tabpanel"
            aria-labelledby="am-fcip-employees-tab"
            tabindex="0"
          >
            <AmCollapse>
              <AmCollapseItem v-for="employee in packEmployees" :key="employee.id" side>
                <template #heading>
                  <div class="am-fcip__info-employee">
                    <div class="am-fcip__info-employee__hero">
                      <AmImagePlaceholder
                        item-class="am-fcip__info-employee__img"
                        :item-data="employee"
                        :trim-string="3"
                      ></AmImagePlaceholder>
                      <div class="am-fcip__info-employee__name">
                        {{ employee.firstName }} {{ employee.lastName }}
                        <span
                          v-if="employee.badge"
                          :style="{ background: employee.badge.color }"
                          class="am-fcip__info-employee__badge"
                        >
                          {{ employee.badge.content }}
                        </span>
                      </div>
                    </div>
                  </div>
                </template>
                <template #default>
                  <div
                    v-if="useDescriptionVisibility(employee.description)"
                    class="am-fcip__info-employee__description ql-description"
                    v-html="employee.description"
                  ></div>
                </template>
              </AmCollapseItem>
            </AmCollapse>
          </div>
          <!-- /Employees -->
        </div>
      </div>

      <!-- Available Service in Packages -->
      <div v-if="customizedOptions.packageServices.visibility" class="am-fcip__include-wrapper">
        <div class="am-fcip__include-heading">
          <span class="am-fcip__include-heading__text">
            {{ `${amLabels.package_includes}:` }}
          </span>
        </div>
        <AmCollapse>
          <AmCollapseItem v-for="book in pack.bookable" :key="book.id" :side="true">
            <template #heading>
              <div class="am-fcip__include-service">
                <AmImagePlaceholder
                  item-class="am-fcip__include-service__img"
                  :item-data="book.service"
                ></AmImagePlaceholder>
                {{ book.service.name + (!pack.sharedCapacity ? ' x' + book.quantity : '') }}
              </div>
            </template>
            <template #default>
              <div class="am-fcip__include-service__info">
                <span>{{ `${amLabels.tab_employees}:` }}</span>
                <AmImagePlaceholder
                  v-for="employee in getServiceEmployees(book).slice(0, 6)"
                  :key="employee.id"
                  item-class="am-fcip__include-service__info-name"
                  :item-data="employee"
                  :trim-string="3"
                ></AmImagePlaceholder>
                <span v-if="getServiceEmployees(book).length > 6">
                  + {{ getServiceEmployees(book).length - 6 }}
                </span>
                <template v-if="useDescriptionVisibility(book.service.description)">
                  <div
                    class="am-fcip__include-service__info-description ql-description"
                    v-html="book.service.description"
                  ></div>
                </template>
              </div>
            </template>
          </AmCollapseItem>
        </AmCollapse>
        <div class="am-fcip__include-footer">
          <span class="am-fcip__include-footer__text">
            {{ amLabels.package_book_service }}
          </span>
        </div>
      </div>
      <!-- /Available Package in Service -->

      <!-- Booking popup -->
      <AmDialog
        v-model="openBooking"
        :append-to-body="true"
        :modal-class="'amelia-v2-booking amelia-v2-booking-dialog'"
        :destroy-on-close="true"
        :center="true"
        :lock-scroll="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :width="bookingDialogWidth"
        @closed="onDialogClosing"
      >
        <CategoryBooking></CategoryBooking>
      </AmDialog>
      <!-- /Booking popup -->
    </template>
  </Content>
  <div v-if="empty" ref="ameliaContainer" class="am-empty">
    <img
      :src="baseUrls.wpAmeliaPluginURL + '/v3/src/assets/img/am-empty-booking.svg'"
      :alt="amLabels.no_package_services"
    />
    <div class="am-empty__heading">
      {{ amLabels.oops }}
    </div>
    <div class="am-empty__subheading">
      {{ amLabels.no_package_services }}
    </div>
    <div class="am-empty__text">
      <a href="https://wpamelia.com/services-and-categories/" rel="nofollow">
        {{ amLabels.add_services_url }}&nbsp;
      </a>
    </div>
  </div>
</template>

<script setup>
// * Components
import Content from '../../../common/CatalogFormConstruction/Content/Content.vue'
import Header from '../../../common/CatalogFormConstruction/Header/Header.vue'
import AmButton from '../../../_components/button/AmButton.vue'
import AmDialog from '../../../_components/dialog/AmDialog.vue'
import AmCollapse from '../../../_components/collapse/AmCollapse.vue'
import AmCollapseItem from '../../../_components/collapse/AmCollapseItem.vue'
import AmImagePlaceholder from '../../../_components/image-placeholder/AmImagePlaceholder.vue'
import CategoryBooking from '../CategoryBooking/CategoryBooking.vue'

// * Vue
import {
  ref,
  reactive,
  inject,
  nextTick,
  computed,
  onMounted,
  onBeforeMount,
  onUnmounted,
  provide,
  watch,
} from 'vue'

// * Vuex
import { useStore } from 'vuex'

// * Composables
import { useFormattedPrice } from '../../../../assets/js/common/formatting.js'
import { useColorTransparency } from '../../../../assets/js/common/colorManipulation.js'
import { usePackageAmount, useBuildPackage } from '../../../../assets/js/public/package.js'
import { usePackageEmployees, usePackageLocations } from '../../../../assets/js/public/catalog.js'
import { useDescriptionVisibility } from '../../../../assets/js/common/helper'
import { useTaxVisibility } from '../../../../assets/js/common/pricing'

// * Global functions
let { previousPage } = inject('changingPageFunctions', {
  previousPage: () => {},
})

// * Page Width
let contentRef = ref()
let pageWidth = inject('containerWidth')

// * Root Settings
const amSettings = inject('settings')

// * Base URLs
const baseUrls = inject('baseUrls')

// * Store
let store = useStore()

// * Shortcode
const shortcodeData = inject('shortcodeData')
const preselected = computed(() => store.getters['entities/getPreselected'])

let backBtnVisibility = ref(preselected.value.package.length !== 1)

// * Entities
let amEntities = inject('amEntities')

// * Customized data
let customizedDataForm = inject('customizedDataForm')

// * Customized options
let customizedOptions = computed(() => {
  return customizedDataForm.value.categoryPackage.options
})

let scrollVisibility = computed(() => {
  if (!('pageScroll' in customizedOptions.value)) return true

  return customizedOptions.value.pageScroll.visibility
})

// * Booking Type (appointment, booking)
let itemType = inject('itemType')

// * Selected category
let categorySelected = inject('categorySelected')
let category = computed(() => {
  return amEntities.value.categories.find((item) => item.id === categorySelected.value)
})

let catNameVisibility = ref(
  preselected.value.package.length !== 1 &&
    customizedOptions.value.packageCategory.visibility &&
    category.value,
)

// * Selected package
let pack = computed(() => {
  return amEntities.value.packages.find((item) => item.id === store.getters['booking/getPackageId'])
})

let activeImage = ref(0)

let tabsActive = ref('description')

let packEmployees = computed(() => {
  return usePackageEmployees(amEntities.value, pack.value, shortcodeData.value)
})

let packLocations = computed(() => {
  return usePackageLocations(amEntities.value, pack.value, shortcodeData.value)
})

let unfilteredEmployees = ref(
  preselected.value.employee.length > 0
    ? amEntities.value.unfilteredEmployees.filter((a) =>
        preselected.value.employee.map((id) => parseInt(id)).includes(a.id),
      )
    : amEntities.value.unfilteredEmployees,
)

function getServiceEmployees(bookable) {
  let employees = []

  if (bookable.providers.length) {
    bookable.providers.forEach((pro) => {
      if (unfilteredEmployees.value.find((a) => a.id === parseInt(pro.id))) {
        employees.push(unfilteredEmployees.value.find((a) => a.id === parseInt(pro.id)))
      }
    })
  } else {
    employees = unfilteredEmployees.value.filter((e) =>
      e.serviceList.find((s) => s.id === bookable.service.id),
    )
  }

  return employees
}

let galleryDialog = ref(false)

function openGallery(index) {
  galleryDialog.value = true
  setActiveGalleryImage(index)
}

function setActiveGalleryImage(index) {
  activeImage.value = index
}

function previousGalleryImage() {
  activeImage.value = activeImage.value <= 0 ? pack.value.gallery.length - 1 : activeImage.value - 1
}

function nextGalleryImage() {
  activeImage.value =
    pack.value.gallery.length - 1 === activeImage.value ? 0 : activeImage.value + 1
}

function focusActiveGalleryThumb() {
  nextTick(() => {
    const thumbElement = document.getElementById(`am-fcip-gallery-thumb-${activeImage.value}`)
    if (thumbElement) thumbElement.focus()
  })
}

function selectPreviousGalleryThumb() {
  previousGalleryImage()
  focusActiveGalleryThumb()
}

function selectNextGalleryThumb() {
  nextGalleryImage()
  focusActiveGalleryThumb()
}

function getGalleryImageLabel(index) {
  return `${amLabels.value.view_all_photos || 'View photo'} ${index + 1} ${
    amLabels.value.of || 'of'
  } ${pack.value.gallery.length}: ${pack.value.name}`
}

function getGalleryImageAlt(index) {
  return `${pack.value.name}, ${index + 1} ${
    amLabels.value.of || 'of'
  } ${pack.value.gallery.length}`
}

function galleryKeydownHandler(e) {
  if (!galleryDialog.value) return
  if (e.key === 'ArrowLeft') {
    previousGalleryImage()
  } else if (e.key === 'ArrowRight') {
    nextGalleryImage()
  }
}

function visibleInfoTabs() {
  const tabs = []

  if (
    useDescriptionVisibility(pack.value.description) &&
    customizedOptions.value.packageDescription.visibility
  ) {
    tabs.push('description')
  }

  if (customizedOptions.value.packageEmployees.visibility) {
    tabs.push('employees')
  }

  return tabs
}

function getInfoTabId(tab) {
  return `am-fcip-${tab}-tab`
}

function setActiveInfoTab(tab, focusTab = false) {
  tabsActive.value = tab

  if (focusTab) {
    nextTick(() => {
      const tabElement = document.getElementById(getInfoTabId(tab))
      if (tabElement) tabElement.focus()
    })
  }
}

function handleInfoTabKeydown(event, currentTab) {
  const tabs = visibleInfoTabs()
  const currentIndex = tabs.indexOf(currentTab)

  if (currentIndex === -1) return

  if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
    event.preventDefault()
    setActiveInfoTab(tabs[(currentIndex - 1 + tabs.length) % tabs.length], true)
  }

  if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
    event.preventDefault()
    setActiveInfoTab(tabs[(currentIndex + 1) % tabs.length], true)
  }

  if (event.key === 'Home') {
    event.preventDefault()
    setActiveInfoTab(tabs[0], true)
  }

  if (event.key === 'End') {
    event.preventDefault()
    setActiveInfoTab(tabs[tabs.length - 1], true)
  }

  if (event.key === 'Enter' || event.key === ' ') {
    event.preventDefault()
    setActiveInfoTab(currentTab)
  }
}

watch(galleryDialog, (val) => {
  if (val) {
    window.addEventListener('keydown', galleryKeydownHandler)
  } else {
    window.removeEventListener('keydown', galleryKeydownHandler)
  }
})

onUnmounted(() => {
  window.removeEventListener('keydown', galleryKeydownHandler)
})

onMounted(() => {
  if (!customizedOptions.value.packageDescription.visibility) tabsActive.value = 'employees'
  if (!useDescriptionVisibility(pack.value.description)) tabsActive.value = 'employees'
})

// * Empty state
let empty = ref(false)

onBeforeMount(() => {
  // ! have to be recalculated basic on package selection on backend now it's working as old catalog form
  empty.value =
    store.getters['entities/getEmployees'].length === 0 || packEmployees.value.length === 0
})

let packageThumbsGallery = computed(() => {
  let thumbs = pack.value.gallery.length ? JSON.parse(JSON.stringify(pack.value.gallery)) : []
  if (pack.value.gallery.length === 1) return []
  thumbs.shift()
  if (thumbs.length > 2) thumbs.splice(2, thumbs.length - 2)
  return thumbs
})

// * Go back
function goBack() {
  itemType.value = ''
  nextTick(() => {
    previousPage()
  })
}

// * Booking Dialog
let openBooking = ref(false)

let bookingDialogWidth = ref('760px')
provide('bookingDialogWidth', bookingDialogWidth)

function bookNow() {
  store.commit('booking/setPackageId', pack.value.id)
  store.commit('booking/setMultipleAppointments', useBuildPackage(0, pack.value))
  store.commit('booking/setMultipleAppointmentsIndex', 0)
  store.commit('booking/setBookableType', 'package')

  nextTick(() => {
    openBooking.value = true
  })
}

let restoreFormData = inject('restoreFormData')

if (restoreFormData.value) {
  bookNow()
}

let stepName = ref('')
provide('stepName', stepName)

function onFinishedBooking() {
  let entity = store.getters['entities/getBookableFromBookableEntities'](
    store.getters['booking/getSelection'],
  )

  let entitySettings = entity.settings ? JSON.parse(entity.settings) : amSettings

  if (
    'general' in entitySettings &&
    'redirectUrlAfterAppointment' in entitySettings.general &&
    entitySettings.general.redirectUrlAfterAppointment
  ) {
    window.location.href = entitySettings.general.redirectUrlAfterAppointment
  } else if (amSettings.general.redirectUrlAfterAppointment) {
    window.location.href = amSettings.general.redirectUrlAfterAppointment
  } else {
    window.location.reload()
  }
}

function onDialogClosing() {
  if (stepName.value && stepName.value === 'CongratulationsStep') {
    onFinishedBooking()
  } else {
    store.commit('entities/setPreselected', store.getters['entities/getOriginalPreselected'])
  }

  bookingDialogWidth.value = '760px'
}

// * Fonts
let amFonts = inject('amFonts')

// * Labels
const labels = inject('labels')

// * Local language short code
const localLanguage = inject('localLanguage')

// * if local lang is in settings lang
let langDetection = computed(() => amSettings.general.usedLanguages.includes(localLanguage.value))

// * Computed labels
let amLabels = computed(() => {
  let computedLabels = reactive({ ...labels })

  if (
    amSettings.customizedData &&
    amSettings.customizedData.cbf &&
    amSettings.customizedData.cbf.categoryPackage.translations
  ) {
    let customizedLabels = amSettings.customizedData.cbf.categoryPackage.translations
    Object.keys(customizedLabels).forEach((labelKey) => {
      if (customizedLabels[labelKey][localLanguage.value] && langDetection.value) {
        computedLabels[labelKey] = customizedLabels[labelKey][localLanguage.value]
      } else if (customizedLabels[labelKey].default) {
        computedLabels[labelKey] = customizedLabels[labelKey].default
      }
    })
  }
  return computedLabels
})

function displayPackageLocationLabel(locations) {
  if (
    locations.length === 1 ||
    (locations.length && locations.every((location) => location.id === locations[0].id))
  ) {
    return locations[0].address ? locations[0].address : locations[0].name
  }
  return amLabels.value.multiple_locations
}

function packageDurationLabel(duration, type) {
  let string = ''
  if (duration > 1) {
    if (type === 'day') string = amLabels.value.expires_days
    if (type === 'week') string = amLabels.value.expires_weeks
    if (type === 'month') string = amLabels.value.expires_months
  } else {
    if (type === 'day') string = amLabels.value.expires_day
    if (type === 'week') string = amLabels.value.expires_week
    if (type === 'month') string = amLabels.value.expires_month
  }
  return string
}

// * Colors
let amColors = inject('amColors')

let cssVars = computed(() => {
  return {
    '--am-c-fcip-success-op20': useColorTransparency(amColors.value.colorSuccess, 0.2),
    '--am-c-fcip-primary-op20': useColorTransparency(amColors.value.colorPrimary, 0.2),
    '--am-c-fcip-text-op80': useColorTransparency(amColors.value.colorMainText, 0.8),
    '--am-c-fcip-text-op60': useColorTransparency(amColors.value.colorMainText, 0.6),
    '--am-c-fcip-text-op03': useColorTransparency(amColors.value.colorMainText, 0.03),
    '--am-c-fcip-text-op20': useColorTransparency(amColors.value.colorMainText, 0.2),
    '--am-c-fcip-btn-op50': useColorTransparency(amColors.value.colorBtnSec, 0.5),
  }
})

let cssGalleryDialogVars = computed(() => {
  return {
    '--am-c-fcip-bgr': amColors.value.colorMainBgr,
    '--am-c-fcip-text': amColors.value.colorMainText,
    '--am-c-fcip-success': amColors.value.colorSuccess,
    '--am-c-fcip-primary': amColors.value.colorPrimary,
    '--am-c-scroll-op30': useColorTransparency(amColors.value.colorPrimary, 0.3),
    '--am-c-scroll-op10': useColorTransparency(amColors.value.colorPrimary, 0.1),
    '--am-font-family': amFonts.fontFamily,
  }
})
</script>

<script>
export default {
  name: 'CategoryPackage',
}
</script>

<style lang="scss">
@import '../../../../../src/assets/scss/common/quill/_quill-mixin.scss';

.amelia-v2-booking {
  // am-    amelia
  // -c-    color
  // -fcip-  form category item package
  // -bgr   background
  #amelia-container {
    .am-fcip {
      --am-c-fcip-header-text: var(--am-c-main-heading-text);
      --am-c-fcip-bgr: var(--am-c-main-bgr);
      --am-c-fcip-text: var(--am-c-main-text);
      --am-c-fcip-success: var(--am-c-success);
      --am-c-fcip-primary: var(--am-c-primary);
      width: 100%;
      padding: 24px;
      border-radius: 10px;

      &__form {
        padding-top: 24px;
      }

      &__header {
        &-top {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 0 16px;

          &.am-tablet {
            flex-wrap: wrap;

            .am-fcip__header-text {
              width: 100%;
              justify-content: space-between;
              margin-bottom: 12px;
            }

            .am-fcip__header-action {
              width: 100%;
              justify-content: space-between;
            }

            &.am-mobile {
              .am-fcip__header {
                &-text {
                  flex-wrap: wrap;
                }

                &-name {
                  width: 100%;
                }

                &-action {
                  flex-wrap: wrap;
                }

                &-discount,
                &-price,
                &-tax {
                  margin-bottom: 6px;
                }

                &-btn {
                  width: 100%;
                  .am-button {
                    width: 100%;
                    margin-top: 6px;
                  }
                }
              }

              .am-fcip__badge {
                margin-left: 0;
              }
            }
          }
        }

        &-text {
          display: flex;
          padding-right: 12px;
          align-items: center;
        }

        &-name {
          display: inline-flex;

          span {
            display: -webkit-box;
            font-size: 28px;
            font-weight: 500;
            line-height: 1.2;
            color: var(--am-c-fcip-header-text);
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        &-action {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          flex: 0 0 auto;
        }

        &-discount {
          display: inline-flex;
          align-items: center;
          height: 28px;
          padding: 0 12px 0;
          border-radius: 14px;
          font-size: 18px;
          font-weight: 500;
          margin: 0 12px 0 0;
          color: var(--am-c-fcip-success);
          background-color: var(--am-c-fcip-success-op20);
        }

        &-price {
          font-size: 18px;
          font-weight: 500;
          margin-right: 20px;
          color: var(--am-c-fcip-primary);
        }

        &-tax {
          display: inline-flex;
          align-items: center;
          height: 28px;
          padding: 0 12px 0;
          border-radius: 14px;
          font-size: 18px;
          font-weight: 500;
          margin: 0 12px 0 0;
          color: var(--am-c-fcip-primary);
          background-color: var(--am-c-fcip-primary-op20);
        }

        &-bottom {
          padding: 0 0 16px;
        }
      }

      &__content {
        &.no-scroll {
          max-height: unset;
          overflow-x: unset;
        }
      }

      &__badge {
        display: inline-flex;
        flex: 0 0 auto;
        align-items: center;
        height: 28px;
        padding: 0 12px 0 8px;
        border-radius: 14px;
        margin-left: 10px;

        &.am-package {
          background: linear-gradient(
            95.75deg,
            var(--am-c-fcip-bgr) -110.8%,
            var(--am-c-warning) 114.33%
          );
          span {
            color: var(--am-c-fcip-bgr);
          }
        }

        span {
          display: block;
          font-size: 18px;
          font-weight: 400;
          line-height: 1;

          &[class*='am-icon'] {
            font-size: 24px;
          }
        }
      }

      &__mini-info {
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        &__inner {
          display: inline-flex;
          align-items: center;
          max-width: 100%;
          padding: 0 8px 0 0;
          margin: 0 0 8px;

          &:last-child {
            padding: 0;
          }

          span {
            font-size: 18px;
            font-weight: 400;
            color: var(--am-c-fcip-text-op80);
            line-height: 1.2;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;

            &[class*='am-icon'] {
              flex: 0 0 auto;
              font-size: 24px;
              color: var(--am-c-fcip-primary);
            }
          }
        }
      }

      &__gallery {
        display: flex;
        position: relative;
        transition: all 0.3s ease-in-out;
        margin: 0 0 32px;
        padding: 0 12px;

        &-hero {
          width: calc(100% - 264px);
          border-top-left-radius: 8px;
          border-bottom-left-radius: 8px;
          margin: 0;
          background-size: cover;
          background-repeat: no-repeat;
          background-position: center;
          transition: all 0.3s ease-in-out;
          overflow: visible;

          &:focus {
            outline: none;
            box-shadow: 0 0 0 2px var(--am-c-fcip-text-op20);
          }

          &.w100 {
            width: 100%;
            padding-top: 25%;
            border-radius: 8px;
            margin-bottom: 0;

            &.am-mobile {
              padding-top: 150px;
            }
          }
        }

        &-thumb {
          position: relative;
          display: inline-block;
          width: calc(100% - 16px);
          padding-top: calc(50% - 16px);
          margin: 0 0 16px 16px;
          background-size: cover;
          background-repeat: no-repeat;
          background-position: center;
          overflow: hidden;
          cursor: pointer;
          float: left;
          transition: all 0.3s ease-in-out;

          &:focus,
          &:focus-visible {
            outline: none;
            box-shadow: inset 0 0 0 2px var(--am-c-fcip-text-op20);
            z-index: 2;
          }

          &:first-child {
            border-top-right-radius: 8px;
          }

          &:last-of-type {
            border-bottom-right-radius: 8px;
            margin-bottom: 0;
          }

          &__wrapper {
            width: 100%;
            max-width: 264px;
            position: relative;

            &:after,
            &:before {
              content: '';
              display: block;
              clear: both;
            }
          }

          &.am-one-thumb {
            padding-top: calc(100% - 16px);
          }
        }

        &-btn {
          position: absolute;
          bottom: 12px;
          right: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          width: calc(264px - 40px);

          &.am-mobile {
            width: calc(100% - 48px);
          }

          &.am-button.am-button--filled {
            --am-c-btn-bgr: var(--am-c-btn-second);
            --am-c-btn-text: var(--am-c-btn-first);
            --am-c-btn-border: var(--am-c-fcip-btn-op50);

            &:not(.is-disabled) {
              &:hover {
                --am-c-btn-bgr: var(--am-c-btn-second);
                --am-c-btn-text: var(--am-c-btn-first);
                --am-c-btn-border: var(--am-c-fcip-btn-op50);
              }
            }
          }

          .am-icon-gallery {
            font-size: 24px;
            margin-right: 4px;
          }
        }
      }

      &__info {
        padding: 0 12px;
        margin: 0 0 32px;

        &-tab {
          font-size: 14px;
          font-weight: 500;
          color: var(--am-c-fcip-text);
          padding: 12px 16px;
          cursor: pointer;

          &:focus,
          &:focus-visible {
            outline: none;
            box-shadow: inset 0 0 0 2px var(--am-c-fcip-primary);
            border-radius: 4px 4px 0 0;
          }

          &:hover {
            color: var(--am-c-fcip-primary);
          }

          &.am-active {
            color: var(--am-c-fcip-primary);
            border-bottom: 3px solid var(--am-c-fcip-primary);
            padding-bottom: 9px;
          }

          &__wrapper {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            position: relative;
          }
        }

        &-content {
          padding: 24px 0;

          .am-collapse-item {
            background-color: var(--am-c-fcip-bgr);

            $count: 100;
            @for $i from 0 through $count {
              &:nth-child(#{$i + 1}) {
                animation: 600ms
                  cubic-bezier(0.45, 1, 0.4, 1.2)
                  #{$i *
                  100}ms
                  am-animation-slide-up;
                animation-fill-mode: both;
              }
            }

            &__heading {
              padding: 12px;
              transition-delay: 0.5s;

              &-side {
                transition-delay: 0s;
              }
            }
          }
        }

        &-service {
          &__desc {
            font-size: 15px;
            line-height: 2;
            word-break: break-word;
            white-space: break-spaces;
            color: var(--am-c-fcip-text-op80);

            * {
              font-size: 15px;
              line-height: 2;
              word-break: break-word;
              white-space: break-spaces;
              color: var(--am-c-fcip-text-op80);
            }

            a {
              color: var(--am-c-fcip-primary);
            }

            &.ql-description {
              @include quill-styles;
            }
          }
        }

        &-employee {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          justify-content: space-between;

          &:last-child {
            margin: 0;
          }

          &__hero {
            display: flex;
            align-items: center;
            justify-content: center;
          }

          &__img {
            width: 54px;
            height: 54px;
            display: flex;
            flex: 0 0 auto;
            align-items: center;
            justify-content: center;
            background-position: center;
            background-size: cover;
            border-radius: 4px;
            border: 1px solid var(--am-c-inp-border);
            color: var(--am-c-fcip-bgr);
            font-size: 18px;
            font-weight: 500;
          }

          &__name {
            font-size: 15px;
            font-weight: 500;
            color: var(--am-c-fcip-text);
            margin: 0 0 0 12px;
          }

          &__badge {
            color: #fff;
            border-radius: 4px;
            padding: 0 4px;
            font-size: 13px;
            line-height: 19px;
          }

          &__price {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 24px;
            font-size: 14px;
            line-height: 1;
            color: var(--am-c-fcip-primary);
            background-color: var(--am-c-fcip-primary-op20);
            padding: 0 8px;
            border-radius: 12px;
          }

          &__description {
            color: var(--am-c-fcis-text);

            &.ql-description {
              @include quill-styles;
            }
          }
        }
      }

      &__include {
        &-wrapper {
          padding: 12px;
          background-color: var(--am-c-fcip-text-op03);
          border-radius: 8px;

          .am-collapse-item {
            background-color: var(--am-c-fcip-bgr);

            $count: 100;
            @for $i from 0 through $count {
              &:nth-child(#{$i + 1}) {
                animation: 600ms
                  cubic-bezier(0.45, 1, 0.4, 1.2)
                  #{$i *
                  100}ms
                  am-animation-slide-up;
                animation-fill-mode: both;
              }
            }

            &__heading {
              padding: 8px;
              transition-delay: 0.5s;

              &-side {
                transition-delay: 0s;
              }
            }
          }
        }

        &-heading {
          display: flex;
          align-items: center;

          &__text {
            display: inline-flex;
            font-size: 14px;
            font-weight: 500;
            color: var(--am-c-fcip-text);
          }
        }

        &-footer {
          display: flex;
          align-items: center;

          &__text {
            display: inline-flex;
            font-size: 13px;
            font-weight: 400;
            color: var(--am-c-fcip-text-op60);
          }
        }

        &-service {
          display: flex;
          align-items: center;
          font-size: 15px;
          font-weight: 500;
          line-height: 1.6;
          /* $shade-900 */
          color: var(--am-c-fcip-text);

          &__img {
            display: inline-flex;
            flex: 0 0 auto;
            align-items: center;
            justify-content: center;
            width: 54px;
            height: 54px;
            color: var(--am-c-fcip-bgr);
            font-size: 18px;
            font-weight: 500;
            line-height: 1;
            border-radius: 4px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            margin: 0 8px 0 0;
          }

          &__employee {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            color: var(--am-c-fcip-bgr);
            font-size: 12px;
            font-weight: 500;
            line-height: 1;
            border-radius: 50%;
            border: 3px solid var(--am-c-fcip-bgr);
            margin: 0 -12px 0 0;
          }

          &__info {
            & > span:first-child {
              font-size: 13px;
              font-weight: 400;
              line-height: 1.384615;
              /* $shade-700 */
              color: var(--am-c-fcip-text-op80);
              margin-right: 20px;
            }

            & > .am-fcip__include-service__info-name {
              display: inline-flex;
              align-items: center;
              justify-content: center;
              width: 36px;
              height: 36px;
              vertical-align: middle;
              font-size: 13px;
              font-weight: 500;
              color: var(--am-c-fcip-bgr);
              margin-left: -10px;
              border-radius: 50%;
              border: 2px solid var(--am-c-fcip-bgr);
              background-color: var(--am-c-fcip-bgr);
              background-size: cover;
              background-position: center;
              background-repeat: no-repeat;
            }

            & > p {
              font-size: 15px;
              font-weight: 400;
              line-height: 1.6;
              /* $shade-700 */
              color: var(--am-c-fcip-text-op80);
              margin: 16px 0 0;

              & * {
                color: var(--am-c-fcip-text-op80);
              }
            }

            & .am-fcip__include-service__info-description {
              &.ql-description {
                @include quill-styles;
              }
            }
          }
        }
      }
    }
  }

  &.amelia-v2-booking-dialog {
    --am-c-fcip-header-text: var(--am-c-main-heading-text);
    --am-c-fcip-bgr: var(--am-c-main-bgr);
    --am-c-fcip-text: var(--am-c-main-text);
    --am-c-fcip-success: var(--am-c-success);
    --am-c-fcip-primary: var(--am-c-primary);
    z-index: 99999999 !important;

    .el-overlay-dialog {
      background-color: rgba(26, 44, 55, 0.5);
    }

    .el-dialog {
      max-width: var(--el-dialog-width, 50%);
      width: 100%;
      border-radius: 8px;
      background-color: transparent;

      &__header {
        min-height: auto;
      }

      &__body {
        padding: 0;
      }
    }
  }

  // - gdp - gallery dialog package
  &.amelia-v2-gdp {
    z-index: 9999999 !important;

    .el-overlay-dialog {
      background-color: rgba(26, 44, 55, 0.5);
    }

    .el-dialog {
      max-width: var(--el-dialog-width);
      width: 100%;
      border-radius: 8px;
      background-color: transparent;
      margin-top: var(--el-dialog-margin-top);

      &__header {
        padding: 0;
      }

      &__headerbtn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 19px;
        height: 19px;
        background-color: var(--am-c-fcip-bgr);
        color: var(--am-c-fcip-text);
        border-radius: 50%;
        z-index: 1000000;

        .el-dialog__close {
          line-height: 1;
        }
      }
    }

    .am-gd {
      border-radius: 8px;
      background-color: var(--am-c-fcip-bgr);
      padding: 0 0 8px;

      * {
        font-family: var(--am-font-family);
      }

      &__display {
        display: flex;
        align-items: center;
        justify-content: center;

        &:focus,
        &:focus-visible {
          outline: none;
          box-shadow: 0 0 0 2px var(--am-c-fcip-primary);
          border-radius: 8px;
        }

        img {
          width: 100%;
          border-radius: 8px;
        }

        &-wrapper {
          position: relative;
          padding: 24px 60px 12px;
        }
      }

      &__arrows {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 100;

        span {
          position: absolute;
          width: 60px;
          height: 100%;
          font-size: 38px;
          color: var(--am-c-fcip-text);
          cursor: pointer;

          &:focus,
          &:focus-visible {
            outline: none;
            box-shadow: inset 0 0 0 2px var(--am-c-fcip-primary);
          }

          &::before {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }

          &:first-child {
            left: 0;
          }

          &:last-child {
            right: 0;
          }
        }
      }

      &__selection {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        line-height: 1.42857;
        color: var(--am-c-fcip-text);
      }

      &__thumb {
        position: relative;
        width: 100px;
        height: 100px;
        flex: 0 0 auto;
        cursor: pointer;
        margin: 0 8px 8px 0;
        background-size: cover;
        background-repeat: no-repeat;
        background-position: center;

        &:focus,
        &:focus-visible {
          outline: none;
          box-shadow: inset 0 0 0 2px var(--am-c-fcip-primary);
        }

        &:last-child {
          margin-right: 0;
        }

        &.am-active {
          &:before {
            content: '';
            position: absolute;
            bottom: -8px;
            left: 0;
            width: 100%;
            height: 4px;
            background-color: var(--am-c-fcip-primary);
          }
        }

        &-wrapper {
          display: flex;
          max-width: calc(100% - 48px);
          width: calc(100% - 48px);
          white-space: nowrap;
          margin: 0 24px;
          overflow-y: hidden;
          padding-bottom: 8px;

          // Main Scroll styles
          &::-webkit-scrollbar {
            height: 6px;
          }

          &::-webkit-scrollbar-thumb {
            border-radius: 6px;
            background: var(--am-c-scroll-op30);
          }

          &::-webkit-scrollbar-track {
            border-radius: 6px;
            background: var(--am-c-scroll-op10);
          }
        }
      }
    }
  }
}
</style>
