<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Navigation, Pagination, Autoplay } from 'swiper/modules'
import { useWordpress } from '@/composables/useWordpress'
import { useHeaderSlider } from '@/composables/useHeaderSlider'
import { useUsefulInfo } from '@/composables/useUsefulInfo'
import { usePhotoChampionships } from '@/data/main/photoChampionships'
import {
  ArrowRight,
  MapPin,
  Instagram,
  Apple,
  Dumbbell,
  Zap,
  Activity,
  X,
  Maximize2,
  ChevronLeft,
  ChevronRight
} from 'lucide-vue-next'

const { posts, fetchPosts } = useWordpress()
const { albumPhotos, lightboxIndex, openLightbox, closeLightbox } = usePhotoChampionships()
const { slides, loading: sliderLoading, error: sliderError } = useHeaderSlider()
const { usefulInfo, loading: infoLoading } = useUsefulInfo()

const isLightboxOpening = ref(false)
const lightboxContentRef = ref<HTMLDivElement | null>(null)

const currentIndex = computed(() => lightboxIndex.value !== null ? lightboxIndex.value : 0)

const openLightboxWithAnimation = async (index: number) => {
  openLightbox(index)

  await nextTick()

  setTimeout(() => {
    isLightboxOpening.value = true
  }, 10)

  document.body.style.overflow = 'hidden'
}

const closeLightboxWithAnimation = () => {
  isLightboxOpening.value = false

  setTimeout(() => {
    closeLightbox()
    document.body.style.overflow = ''
  }, 300)
}

const goToPrevious = (e?: MouseEvent) => {
  if (e) {
    e.stopPropagation()
  }
  if (lightboxIndex.value !== null && albumPhotos.value.length > 1) {
    const newIndex = lightboxIndex.value === 0 ? albumPhotos.value.length - 1 : lightboxIndex.value - 1
    lightboxIndex.value = newIndex
  }
}

const goToNext = (e?: MouseEvent) => {
  if (e) {
    e.stopPropagation()
  }
  if (lightboxIndex.value !== null && albumPhotos.value.length > 1) {
    const newIndex = lightboxIndex.value === albumPhotos.value.length - 1 ? 0 : lightboxIndex.value + 1
    lightboxIndex.value = newIndex
  }
}

const onOverlayClick = (e: MouseEvent) => {
  if (e.target === e.currentTarget) {
    closeLightboxWithAnimation()
  }
}

const handleKeyDown = (e: KeyboardEvent) => {
  if (lightboxIndex.value !== null) {
    if (e.key === 'Escape') {
      closeLightboxWithAnimation()
    } else if (e.key === 'ArrowLeft') {
      goToPrevious()
    } else if (e.key === 'ArrowRight') {
      goToNext()
    }
  }
}

onMounted(() => {
  fetchPosts({ per_page: 3 })
  window.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
  document.body.style.overflow = ''
})
</script>

<template>
  <div class="home-page overflow-hidden bg-slate-950 text-white">
    <!-- Slider -->
    <section class="relative h-screen max-h-[800px] bg-slate-900">
      <Swiper :modules="[Navigation, Pagination, Autoplay]" :slides-per-view="1" :navigation="true"
        :pagination="{ clickable: true }" :autoplay="{ delay: 5000 }" class="h-full">
        <SwiperSlide v-for="(slide, index) in slides" :key="index" class="relative">
          <img :src="slide.image" :alt="slide.title"
            class="absolute inset-0 w-full h-full object-cover object-top opacity-60" />
          <div class="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/20 to-transparent"></div>
          <div class="container h-full">
            <div class="row h-100 align-items-end pb-5 relative z-10">
              <div class="col-12 col-lg-10">
                <h1
                  class="text-3xl sm:text-4xl md:text-6xl xl:text-7xl 2xl:text-8xl font-black uppercase italic tracking-tighter leading-none mb-4">
                  <span class="text-orange-600">{{ slide.title.split(' ')[0] }}</span><br />
                  {{ slide.title.split(' ').slice(1).join(' ') }}
                </h1>
                <p
                  class="text-base sm:text-lg md:text-xl xl:text-lg text-slate-300 max-w-2xl font-medium tracking-wide">
                  {{ slide.description }}
                </p>
              </div>
            </div>
          </div>
        </SwiperSlide>
      </Swiper>
    </section>

    <!-- Useful Info -->
    <section class="py-5 bg-slate-950">
      <div class="container py-5">
        <div class="row align-items-end mb-5">
          <div class="col-12 col-md-8">
            <h2 class="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-black uppercase tracking-tighter italic mb-4">
              Полезная <span class="text-orange-600">информация</span>
            </h2>
            <p class="text-slate-400 text-base sm:text-lg max-w-2xl mb-0">
              Все о мире фитнеса и бодибилдинга: от основ анатомии до тонкостей спортивных добавок.
            </p>
          </div>
          <div class="col-12 col-md-4 text-md-end mt-4 mt-md-0">
            <div class="d-inline-block h-1 w-24 bg-orange-600 mb-2"></div>
          </div>
        </div>

        <!-- Состояние загрузки -->
        <div v-if="infoLoading" class="row g-4">
          <div v-for="i in 4" :key="i" class="col-12 col-md-6 col-lg-3">
            <div class="bg-slate-900 border border-slate-800 p-6 sm:p-8 rounded-2xl">
              <div class="h-6 w-32 bg-slate-800 animate-pulse rounded mb-4"></div>
              <div class="space-y-2">
                <div class="h-3 bg-slate-800 animate-pulse rounded"></div>
                <div class="h-3 bg-slate-800 animate-pulse rounded"></div>
                <div class="h-3 bg-slate-800 animate-pulse rounded w-3/4"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- Карточки с данными -->
        <div v-else class="row g-4">
          <div v-for="info in usefulInfo" :key="info.title" class="col-12 col-md-6 col-lg-3">
            <router-link :to="info.link" class="text-decoration-none">
              <div
                class="group h-100 bg-slate-900 border border-slate-800 p-6 sm:p-8 rounded-2xl hover:bg-slate-800 transition-all duration-300 hover:-translate-y-2 relative overflow-hidden">
                <div class="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
                  <component :is="info.icon" :size="80" />
                </div>
                <h3
                  class="text-lg sm:text-xl font-bold uppercase mb-4 text-orange-500 group-hover:text-white transition-colors relative z-10">
                  {{ info.title }}
                </h3>
                <p
                  class="text-slate-400 text-xs sm:text-sm leading-relaxed mb-6 group-hover:text-slate-200 transition-colors relative z-10 line-clamp-4">
                  {{ info.description }}
                </p>
                <span
                  class="text-xs font-black uppercase tracking-widest flex items-center gap-2 group-hover:gap-4 transition-all text-white">
                  Подробнее
                  <ArrowRight :size="14" class="text-orange-600" />
                </span>
              </div>
            </router-link>
          </div>
        </div>
      </div>
    </section>

    <!-- Athletes Section -->
    <section class="py-5 bg-slate-900 border-y border-slate-800 overflow-hidden">
      <div class="container py-5">
        <div class="row g-5 align-items-center">
          <div class="col-12 col-lg-6">
            <div class="row g-4 align-items-center group">
              <div class="col-12 col-md-7">
                <router-link to="/biography/alexander"
                  class="relative block aspect-[4/5] rounded-3xl overflow-hidden shadow-2xl shadow-orange-950/20 text-decoration-none">
                  <img src="/src/assets/images/main/alexander.jpg" alt="Александр Сахаров"
                    class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
                  <div class="absolute inset-0 bg-gradient-to-t from-slate-950 via-transparent to-transparent"></div>
                  <div class="absolute bottom-4 sm:bottom-6 left-4 sm:left-6 text-white">
                    <h3 class="text-xl sm:text-2xl md:text-3xl font-black uppercase italic tracking-tighter mb-1">
                      Александр Сахаров</h3>
                    <p class="text-orange-500 font-bold uppercase tracking-widest text-xs mb-0">Бодибилдинг тренер</p>
                  </div>
                </router-link>
              </div>
              <div class="col-12 col-md-5">
                <div class="space-y-4">
                  <router-link to="/biography/alexander" class="text-decoration-none group/title block">
                    <h4
                      class="text-xl sm:text-2xl font-bold uppercase tracking-tighter leading-none text-white group-hover/title:text-orange-500 transition-colors">
                      Сила и воля</h4>
                  </router-link>
                  <p class="text-slate-400 text-xs sm:text-sm">Александр Сахаров - профессиональный бодибилдер, эксперт
                    по силовым
                    тренировкам и набору мышечной массы.</p>
                  <div class="flex gap-4">
                    <a href="https://www.instagram.com/caxapob73/" target="_blank"
                      class="w-8 h-8 sm:w-10 sm:h-10 rounded-full border border-slate-700 flex items-center justify-center text-white hover:bg-orange-600 hover:border-orange-600 transition-all text-decoration-none">
                      <Instagram :size="16" class="sm:w-[18px] sm:h-[18px]" />
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="col-12 col-lg-6">
            <div class="row g-4 align-items-center flex-row-reverse group">
              <div class="col-12 col-md-7">
                <router-link to="/biography/lyudmila"
                  class="relative block aspect-[4/5] rounded-3xl overflow-hidden shadow-2xl shadow-orange-950/20 text-decoration-none">
                  <img src="/src/assets/images/main/ludmila.jpg" alt="Людмила Богатырь"
                    class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
                  <div class="absolute inset-0 bg-gradient-to-t from-slate-950 via-transparent to-transparent"></div>
                  <div class="absolute bottom-4 sm:bottom-6 left-4 sm:left-6 text-white text-left">
                    <h3 class="text-xl sm:text-2xl md:text-3xl font-black uppercase italic tracking-tighter mb-1">
                      Людмила Богатырь</h3>
                    <p class="text-orange-500 font-bold uppercase tracking-widest text-xs mb-0">Фитнес Тренер</p>
                  </div>
                </router-link>
              </div>
              <div class="col-12 col-md-5 text-md-end">
                <div class="space-y-4">
                  <router-link to="/biography/lyudmila" class="text-decoration-none group/title block">
                    <h4
                      class="text-xl sm:text-2xl font-bold uppercase tracking-tighter leading-none text-white group-hover/title:text-orange-500 transition-colors">
                      Грация и форма</h4>
                  </router-link>
                  <p class="text-slate-400 text-xs sm:text-sm text-md-end">Людмила Богатырь - профессионал в категории
                    фитнес,
                    специалист по коррекции фигуры и женскому тренингу.</p>
                  <div class="flex gap-4 justify-content-md-end">
                    <a href="https://www.instagram.com/bogatir0612/" target="_blank"
                      class="w-8 h-8 sm:w-10 sm:h-10 rounded-full border border-slate-700 flex items-center justify-center text-white hover:bg-orange-600 hover:border-orange-600 transition-all text-decoration-none">
                      <Instagram :size="16" class="sm:w-[18px] sm:h-[18px]" />
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Photo Album -->
    <section class="py-5 bg-slate-950">
      <div class="container py-5">
        <div class="row text-center mb-5">
          <div class="col-12">
            <h2 class="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-black uppercase italic tracking-tighter mb-4">
              Фотоальбом с <span class="text-orange-600">чемпионатов</span>
            </h2>
            <p class="text-slate-400 text-sm sm:text-base max-w-xl mx-auto">Яркие моменты триумфа и соревновательного
              пути.</p>
          </div>
        </div>

        <div class="row g-3">
          <div v-for="(photo, index) in albumPhotos" :key="index" class="col-6 col-md-4 col-lg-3">
            <div class="group relative aspect-square bg-slate-900 overflow-hidden cursor-pointer rounded-lg"
              @click="openLightboxWithAnimation(index)">
              <img :src="photo"
                class="w-full h-full object-cover object-top grayscale group-hover:grayscale-0 transition-all duration-500 group-hover:scale-110"
                alt="Championship photo" />
              <div class="absolute inset-0 bg-orange-600/20 opacity-0 group-hover:opacity-100 transition-opacity"></div>
              <div
                class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity scale-50 group-hover:scale-100 duration-300">
                <Maximize2 :size="24" class="sm:w-[32px] sm:h-[32px] text-white drop-shadow-lg" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Map Section -->
    <section class="h-[300px] sm:h-[400px] md:h-[500px] relative">
      <div class="absolute inset-0">
        <iframe
          src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2996.483883864749!2d69.29924012170245!3d41.320090181150476!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x38aef4dab71f6f99%3A0xa9d7387450f6b09f!2sozonefc%20-%20darhan!5e0!3m2!1sen!2s!4v1600777394958!5m2!1sen!2s"
          width="100%" height="450" frameborder="0" style="border:0;" :allowfullscreen="true" aria-hidden="false"
          tabindex="0"></iframe>
      </div>
      <div
        class="absolute inset-0 pointer-events-none bg-gradient-to-b from-slate-950/40 via-transparent to-slate-950/40">
      </div>
    </section>

    <!-- Lightbox с плавными анимациями и навигацией -->
    <Transition enter-active-class="transition duration-300 ease-out" enter-from-class="opacity-0"
      enter-to-class="opacity-100" leave-active-class="transition duration-300 ease-in" leave-from-class="opacity-100"
      leave-to-class="opacity-0">
      <div v-if="lightboxIndex !== null"
        class="fixed inset-0 z-[100] flex items-center justify-center p-2 sm:p-4 md:p-12 bg-slate-950/95 backdrop-blur-sm"
        @click="onOverlayClick">
        <div ref="lightboxContentRef" class="relative max-w-7xl w-full flex flex-col items-center" :class="{
          'scale-100 opacity-100': isLightboxOpening,
          'scale-95 opacity-0': !isLightboxOpening
        }" :style="{
          transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
        }">
          <button @click.stop="closeLightboxWithAnimation"
            class="absolute -top-8 sm:-top-12 right-0 text-white hover:text-orange-500 transition-colors border-0 bg-transparent z-20"
            :class="{
              'scale-100 opacity-100': isLightboxOpening,
              'scale-50 opacity-0': !isLightboxOpening
            }" :style="{
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.1s'
            }">
            <X :size="28" class="sm:w-[40px] sm:h-[40px]" />
          </button>

          <button v-if="albumPhotos.length > 1" @click.stop="goToPrevious"
            class="absolute left-2 sm:left-4 top-1/2 -translate-y-1/2 w-8 h-8 sm:w-12 sm:h-12 rounded-full bg-slate-900/80 backdrop-blur-sm border border-slate-700 flex items-center justify-center text-white hover:bg-orange-600 hover:border-orange-600 transition-all z-20"
            :class="{
              'translate-x-0 opacity-100': isLightboxOpening,
              '-translate-x-4 opacity-0': !isLightboxOpening
            }" :style="{
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s'
            }">
            <ChevronLeft :size="20" class="sm:w-[24px] sm:h-[24px]" />
          </button>

          <button v-if="albumPhotos.length > 1" @click.stop="goToNext"
            class="absolute right-2 sm:right-4 top-1/2 -translate-y-1/2 w-8 h-8 sm:w-12 sm:h-12 rounded-full bg-slate-900/80 backdrop-blur-sm border border-slate-700 flex items-center justify-center text-white hover:bg-orange-600 hover:border-orange-600 transition-all z-20"
            :class="{
              'translate-x-0 opacity-100': isLightboxOpening,
              'translate-x-4 opacity-0': !isLightboxOpening
            }" :style="{
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s'
            }">
            <ChevronRight :size="20" class="sm:w-[24px] sm:h-[24px]" />
          </button>

          <img v-if="lightboxIndex !== null" :key="currentIndex" :src="albumPhotos[lightboxIndex]"
            class="max-w-full max-h-[85vh] object-contain shadow-2xl border border-slate-800 rounded-lg relative z-10"
            :class="{
              'scale-100 opacity-100': isLightboxOpening,
              'scale-95 opacity-0': !isLightboxOpening
            }" :style="{
              transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)'
            }" />

          <div v-if="albumPhotos.length > 1"
            class="absolute -bottom-8 sm:-bottom-12 left-1/2 -translate-x-1/2 px-3 sm:px-4 py-1 sm:py-2 bg-slate-900/90 backdrop-blur-sm border border-slate-800 rounded-full text-white text-xs sm:text-sm z-20"
            :class="{
              'translate-y-0 opacity-100': isLightboxOpening,
              'translate-y-4 opacity-0': !isLightboxOpening
            }" :style="{
              transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.2s'
            }">
            {{ lightboxIndex + 1 }} / {{ albumPhotos.length }}
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style>
.swiper-button-next,
.swiper-button-prev {
  @apply text-orange-600;
}

.swiper-pagination-bullet-active {
  @apply bg-orange-600;
}

.h-100 {
  height: 100%;
}

.justify-content-md-end {
  @media (min-width: 768px) {
    justify-content: flex-end;
  }
}
</style>
