<script setup lang="ts">
import type { Tag } from '@/types'

const props = withDefaults(defineProps<{
  tag: Tag
  size?: 'small' | 'default' | 'large'
  closable?: boolean
  clickable?: boolean
}>(), {
  size: 'default',
  closable: false,
  clickable: false
})

const emit = defineEmits<{
  click: [tag: Tag]
  close: [tag: Tag]
}>()

// 根据背景色计算对比色（黑或白）
function getContrastColor(hexColor: string): string {
  const hex = hexColor.replace('#', '')
  const r = parseInt(hex.substring(0, 2), 16)
  const g = parseInt(hex.substring(2, 4), 16)
  const b = parseInt(hex.substring(4, 6), 16)
  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
  return luminance > 0.5 ? '#000000' : '#ffffff'
}

function handleClick() {
  if (props.clickable) {
    emit('click', props.tag)
  }
}

function handleClose(e: Event) {
  e.stopPropagation()
  emit('close', props.tag)
}
</script>

<template>
  <span
    class="tag-badge"
    :class="[
      `tag-badge--${size}`,
      { 'tag-badge--clickable': clickable }
    ]"
    :style="tag.color ? {
      backgroundColor: tag.color,
      color: getContrastColor(tag.color),
      borderColor: tag.color
    } : {}"
    @click="handleClick"
  >
    <span v-if="tag.icon" class="tag-icon">{{ tag.icon }}</span>
    <span class="tag-name">{{ tag.name }}</span>
    <span v-if="closable" class="tag-close" @click="handleClose">
      <el-icon><Close /></el-icon>
    </span>
  </span>
</template>

<style lang="scss" scoped>
.tag-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  background-color: #f0f0f0;
  color: #666;
  border: 1px solid #e0e0e0;
  transition: all 0.2s;

  &--small {
    padding: 1px 6px;
    font-size: 11px;
  }

  &--large {
    padding: 4px 12px;
    font-size: 14px;
  }

  &--clickable {
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }

  .tag-icon {
    font-size: 1em;
  }

  .tag-name {
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .tag-close {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 2px;
    cursor: pointer;
    opacity: 0.6;

    &:hover {
      opacity: 1;
    }

    .el-icon {
      font-size: 10px;
    }
  }
}
</style>
