<template>
  <div class="tags" @click="focusInput">
    <span v-for="(tag, i) in modelValue" :key="tag" class="tag">
      {{ tag }}
      <span class="rm" @click.stop="removeTag(i)">&times;</span>
    </span>
    <input
      ref="input"
      v-model="newTag"
      @keydown.enter.prevent="addTag"
      @keydown.backspace="handleBackspace"
      :placeholder="modelValue?.length ? '' : placeholder"
    />
  </div>
</template>

<script setup>
const props = defineProps({
  modelValue: { type: Array, default: () => [] },
  placeholder: { type: String, default: "Add tag..." },
});

const emit = defineEmits(["update:modelValue"]);

const input = ref(null);
const newTag = ref("");

const focusInput = () => {
  input.value?.focus();
};

const addTag = () => {
  const tag = newTag.value.trim();
  if (tag && !props.modelValue.includes(tag)) {
    emit("update:modelValue", [...props.modelValue, tag]);
  }
  newTag.value = "";
};

const removeTag = (index) => {
  const tags = [...props.modelValue];
  tags.splice(index, 1);
  emit("update:modelValue", tags);
};

const handleBackspace = () => {
  if (!newTag.value && props.modelValue.length) {
    removeTag(props.modelValue.length - 1);
  }
};
</script>

<style scoped>
.tags {
  border: 1px dashed var(--border);
  padding: 3px 5px;
  display: flex;
  flex-wrap: wrap;
  gap: 3px;
  background: var(--input-bg);
  min-height: 30px;
  align-items: center;
  cursor: text;
}

.tags:focus-within {
  border-color: var(--candle);
  border-style: solid;
}

.tag {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  padding: 1px 6px;
  border: 1px dashed var(--border-d);
  font-size: 11px;
  color: var(--text);
  background: var(--surface);
}

.rm {
  color: var(--text-faint);
  cursor: pointer;
  font-size: 12px;
  line-height: 1;
}

.rm:hover {
  color: var(--ember);
}

.tags input {
  border: none;
  background: transparent;
  padding: 1px 4px;
  font-size: 11px;
  font-family: "Commit Mono", monospace;
  color: var(--text);
  flex: 1;
  min-width: 80px;
  outline: none;
}
</style>
