<template>
  <UCard>
    <div class="flex flex-col items-center justify-center gap-4 p-4">
      <div class="flex items-center gap-4">
        <UButton
          icon="i-lucide-minus"
          size="lg"
          variant="outline"
          @click="increment(-1)"
        />
        <div class="text-4xl font-bold w-16 text-center">
          {{ count }}
        </div>
        <UButton
          icon="i-lucide-plus"
          size="lg"
          variant="outline"
          @click="increment(1)"
        />
      </div>
      <UButton
        v-if="recordId"
        icon="i-lucide-rotate-ccw"
        size="md"
        variant="ghost"
        @click="reset()"
      >
        {{ $t("counter.reset") }}
      </UButton>
    </div>
  </UCard>
</template>

<script setup lang="ts">
const { fetchCurrentCount, subscribeToChanges, unsubscribe, reset, increment }
  = useCounter()
const { count, recordId } = storeToRefs(useCounter())

// Fetch the current count once on page load
fetchCurrentCount()

onMounted(() => {
  // Subscribe to realtime changes of the count
  subscribeToChanges()
})

// Unsubscribe for cleanup
onUnmounted(() => {
  unsubscribe()
})
</script>
