<template>
  <article class="PriceCard card">
    <div class="bottom">
      <div class="bg-edit">
        <Icon class="icon" name="uil:pen" mode="svg" />
      </div>
      <div class="bg-delete">
        <Icon class="icon" name="uil:trash-alt" mode="svg" />
      </div>
    </div>
    <div
      ref="top"
      class="top flex-col"
      :style="{ left, transition }"
    >
      <header>
        <div class="name-price">
          <span>{{ card.name || 'Kein Name' }}</span>
          <span>{{ intl.format(+replaceComma(card.price))}}</span>
        </div>
        <div v-if="$device.isDesktop" class="flex-row gap-default">
          <PpButton class="icon-button" @click="update()">
            <Icon class="icon" name="uil:pen" mode="svg" />
          </PpButton>
          <PpButton class="icon-button" @click="deleteCard()">
            <Icon class="icon" name="uil:trash-alt" mode="svg" />
          </PpButton>
        </div>
      </header>

      <main class="wrapper">
        <div class="info flex-col">
          <div class="price">
            <Icon class="icon" name="uil:toilet-paper" mode="svg" />
            <span class="value">{{ intl.format(card.ppr) }}</span>
          </div>
          <span class="pro">Pro 1 {{ card.roles ? `(${card.roles})` : '' }}</span>
        </div>
        <div class="info flex-col">
          <div class="price">
            <Icon class="icon" name="uil:file-landscape" mode="svg" />
            <span class="value">{{ intl.format(card.pps) }}</span>
          </div>
          <span class="pro">Pro 100 {{ card.sheets ? `(${card.sheets})` : '' }}</span>
        </div>
        <div class="info flex-col">
          <div class="price">
            <Icon class="icon" name="uil:layer-group" mode="svg" />
            <span class="value">{{ intl.format(card.ppl) }}</span>
          </div>
          <span class="pro">Pro 100 {{ card.layers ? `(${card.layers})` : '' }}</span>
        </div>
      </main>
    </div>
  </article>
</template>

<script setup lang="ts">
import type { Card } from '../../../shared/Card'

type Props = {
  deletable: boolean
  card: Card
}

const { card } = defineProps<Props>()
const emit = defineEmits(['remove', 'update'])

const top = useTemplateRef('top')
const left = shallowRef<string>('0')
const transition = shallowRef<string>('none')

const intl = Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
})

const { lengthX } = useSwipe(top, {
  passive: false,
  threshold: 5,
  onSwipe() {
    if (lengthX.value != 0) {
      left.value = `${-clamp(lengthX.value, -100, 100)}px`
    }
  },
  onSwipeEnd() {
    if (lengthX.value < -50) update()
    if (lengthX.value > 50) deleteCard()
    transition.value = '150ms'

    setTimeout(() => {
      left.value = '0'
      setTimeout(() => {
        transition.value = 'none'
      }, 50)
    }, 100)
  },
})

const update = () => emit('update')

const deleteCard = () => emit('remove')
</script>
