<script setup lang="ts">
import { ref, watch } from 'vue'
import type { Card } from '../types'

const props = defineProps<{ card: Card }>()
const emit = defineEmits<{
  toggle: [complete: boolean]
  'save-text': [text: string]
  delete: []
}>()

const text = ref(props.card.text)
watch(
  () => props.card.text,
  (value) => {
    text.value = value
  },
)

function commit() {
  const next = text.value.trim()
  if (next === '') {
    text.value = props.card.text // the API requires a non-empty text
    return
  }
  if (next !== props.card.text) emit('save-text', next)
}
</script>

<template>
  <li class="card-row" :class="{ 'card-row--done': card.complete }">
    <span class="card-row__handle" aria-hidden="true" title="Drag to reorder">⠿</span>

    <input
      class="card-row__check"
      type="checkbox"
      :checked="card.complete"
      :aria-label="card.complete ? 'Mark as not done' : 'Mark as done'"
      @change="emit('toggle', ($event.target as HTMLInputElement).checked)"
    />

    <input
      v-model="text"
      class="card-row__text"
      type="text"
      maxlength="1000"
      aria-label="Card text"
      @blur="commit"
      @keyup.enter="($event.target as HTMLInputElement).blur()"
    />

    <button type="button" class="card-row__delete" aria-label="Delete card" @click="emit('delete')">
      ✕
    </button>
  </li>
</template>
