<script setup>

const model = defineModel({ type: Array, required: true });

// https://vuejs.org/guide/components/v-model.html#basic-usage
const props = defineProps({
  placeholder: String,
  modelValue: {
    type: Array,
    default: []
  },
  id: String
});

function onKey(event) {
  const newTag = event.target.value;
  if (event.key === ',' || event.key === ' ' || event.key === 'Enter' || event.key === 'Tab') {
    event.target.value = '';

    if (newTag) model.value.push(newTag);
    else if (event.key === 'Enter' || event.key === 'Tab') return;

    event.preventDefault();
  } else if (event.key === 'Backspace' && !newTag) {
    onRemoveIndex(model.value.length - 1);
    event.preventDefault();
  }
}

function onBlur() {
  const newTag = event.target.value;
  event.target.value = '';
  if (newTag) model.value.push(newTag);
}

function onRemoveIndex(index) {
  model.value.splice(index, 1);
}

</script>

<template>
  <div class="pankow-tag-input">
    <div class="pankow-tag-input-tag" v-for="(tag, index) in model" :key="index">{{ tag }} <i class="fa-solid fa-xmark pankow-tag-input-tag-remove" @click="onRemoveIndex(index)"></i></div>
    <input class="pankow-tag-input-input" :id="id" :placeholder="placeholder" :autofocus="$attrs['autofocus']" @keydown="onKey($event)" @blur="onBlur"/>
  </div>
</template>

<style>

.pankow-tag-input {
  display: inline-flex;
  white-space: nowrap;
  position: relative;
  border: 1px solid var(--pankow-input-border-color);
  color: var(--pankow-text-color);
  background-color: var(--pankow-input-background-color);
  padding: 4px 4px;
  border-radius: var(--pankow-border-radius);
  transition: border-color 250ms;
  overflow: auto;
}

.pankow-tag-input-tag {
  background-color: var(--pankow-color-primary);
  color: white;
  display: inline-block;
  padding: 2px 4px;
  margin: 0 2px;
  border-radius: var(--pankow-border-radius);
}

.pankow-tag-input-tag-remove {
  cursor: pointer;
}

.pankow-tag-input-tag:has(.pankow-tag-input-tag-remove:hover) {
  background-color: var(--pankow-color-primary-hover);
  opacity: 0.8;
}

.pankow-tag-input-input {
  flex-grow: 1;
  font-size: 14px;
  display: inline-block;
  border: none;
  background: transparent;
  color: var(--pankow-text-color);
  margin-left: 4px;
}

.pankow-tag-input-input:active,
.pankow-tag-input-input:hover,
.pankow-tag-input-input:focus {
  border: none;
  outline: none;
}

.pankow-tag-input.has-error {
  border: 1px solid var(--pankow-color-danger) !important;
}

</style>