<template>
  <div ref="target" class="product">
    <UDrawer
      v-if="isMobile"
      v-model:open="open"
      :class="{ animated: !isSwiping }"
      :style="{ top }"
    >
      <ProductImages />

      <div class="product-info">
        <div class="product-info__title">
          <ProductPrice :price="currentVariant?.options[0]?.price" />

          <div>
            фотомодель
          </div>
        </div>

        <h1>
          {{ productsData?.name }}
        </h1>

        <div class="mt20">
          <UButton
            icon="lucide:shopping-cart"
            class="justify-content-center w-100 d-flex"
            label="Добавить"
            size="xl"
            @click="open = !open"
          />
        </div>
      </div>

      <template #body>
        <ProductDescription />
      </template>
    </UDrawer>

    <ProductImages v-if="!isMobile" />
    <ProductDescription v-if="!isMobile" />
  </div>
</template>

<script setup lang="ts">
import type { UseSwipeDirection } from '@vueuse/core'
import { useMediaQuery, useSwipe } from '@vueuse/core'
import { computed, shallowRef } from 'vue'
import ProductPrice from '~/components/ProductPrice.vue'
import { useCurrentProduct, useProduct } from '~/composables'

const { productsData } = useProduct()
const isMobile = useMediaQuery('(max-width: 1280px)')
const open = ref(false)
const target = shallowRef<HTMLElement | null>(null)
const targetHeight = computed(() => target.value?.offsetHeight)
const top = shallowRef('0')

const { isSwiping, lengthY } = useSwipe(
  target,
  {
    passive: false,
    onSwipe(e: TouchEvent) {
      if (targetHeight.value) {
        if (lengthY.value > 100) {
          open.value = true
        }
      }
    },
    onSwipeEnd(e: TouchEvent, direction: UseSwipeDirection) {
      console.log('lengthY.value', lengthY.value)
      if (lengthY.value > 100 && targetHeight.value && (Math.abs(lengthY.value) / targetHeight.value) >= 0.5) {
        open.value = true
      }
    },
  },
)

const { currentVariant } = useCurrentProduct()
</script>

<style scoped lang="scss">
@use '~/assets/scss/utils' as *;

.product {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: row;

  @media (max-width: 768px) {
    flex-direction: column;
    align-items: center;
  }
}

.product-info {
  padding-inline: 15px;
  position: absolute;
  bottom: 40px;
  z-index: 10;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 10px;

  &__title {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
}
</style>
