<template>
  <section class="content flex-col">
    <div class="pc-wrapper flex-col">
      <PpPriceCard
        v-for="(card, index) in cards"
        :key="card.uuid"
        :deletable="cards.length > 1"
        :card="card"
        @update="updateCard(card, index)"
        @remove="removeCard(card)"
      />
    </div>
  </section>
  <PpToolbar>
    <PpButton class="mini-button text-white" @click="addCard">
      <Icon class="icon" name="uil:plus" mode="svg" />
      <span>Hinzufügen</span>
    </PpButton>
  </PpToolbar>
</template>

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

const createCard = (uuid : string) => ({
  uuid,
  name: '',
  price: 0,
  roles: 0,
  sheets: 0,
  layers: 0,
})

const cards = useState('cards', () => [
  createCard(crypto.randomUUID()),
])

onMounted(() => {
  const fromStorage = JSON.parse(localStorage.getItem('cards') ?? '[]')
  cards.value = fromStorage.length !== 0 ? fromStorage : cards.value
})

const addCard = () => {
  cards.value.push(createCard(crypto.randomUUID()))
}

const removeCard = (card : Card) => {
  cards.value = cards.value.filter(element => element.uuid !== card.uuid)
  updateLocalStorage()
}

const updateCard = (card : Card, index : number) => {
  cards.value[index] = card
  updateLocalStorage()
}

const updateLocalStorage = () => {
  localStorage.setItem('cards', JSON.stringify(cards.value))
}

const sort = () => {}
</script>
