<template>
  <div class="tags-select" :class="{ disabled: disabled }">
    <button 
      v-for="option in options" 
      :key="option.value"
      class="tag-option"
      :class="{ active: isSelected(option.value) }"
      :style="{ '--tag-color': option.color || defaultColor }"
      :disabled="disabled"
      @click="!disabled && toggleOption(option.value)"
    >
      <span v-if="option.icon" class="tag-icon">{{ option.icon }}</span>
      {{ option.label }}
    </button>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number, Array, null],
    default: null
  },
  options: {
    type: Array,
    default: () => []
    // Формат: [{ value: 1, label: 'Name', color: '#00d4aa', icon: '🔥' }]
  },
  multiple: {
    type: Boolean,
    default: false
  },
  allowDeselect: {
    type: Boolean,
    default: true
  },
  defaultColor: {
    type: String,
    default: 'var(--accent)'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// Проверка выбрана ли опция
const isSelected = (value) => {
  if (props.multiple) {
    return Array.isArray(props.modelValue) && props.modelValue.includes(value)
  }
  return props.modelValue === value
}

// Переключение опции
const toggleOption = (value) => {
  let newValue
  
  if (props.multiple) {
    const current = Array.isArray(props.modelValue) ? [...props.modelValue] : []
    const index = current.indexOf(value)
    
    if (index > -1) {
      if (props.allowDeselect) {
        current.splice(index, 1)
      }
    } else {
      current.push(value)
    }
    newValue = current
  } else {
    // Single select
    if (props.modelValue === value && props.allowDeselect) {
      newValue = null
    } else {
      newValue = value
    }
  }
  
  emit('update:modelValue', newValue)
  emit('change', newValue)
}
</script>

<style scoped>
.tags-select {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-option {
  padding: 8px 14px;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 6px;
  color: var(--text-secondary);
  font-family: inherit;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  cursor: pointer;
  transition: all 0.15s;
}

.tag-option:hover {
  border-color: var(--tag-color);
  color: var(--tag-color);
}

.tag-option.active {
  background: var(--tag-color);
  border-color: var(--tag-color);
  color: #000;
}

.tags-select.disabled .tag-option {
  cursor: default;
  opacity: 0.7;
}

.tags-select.disabled .tag-option:hover {
  border-color: rgba(255, 255, 255, 0.08);
  color: var(--text-secondary);
}

.tags-select.disabled .tag-option.active:hover {
  background: var(--tag-color);
  border-color: var(--tag-color);
  color: #000;
}

.tag-icon {
  font-size: 14px;
  margin-right: 4px;
}
</style>
