<template>
  <div class="user-avatar" :class="sizeClass">
    <img
      v-if="avatar"
      :src="avatar"
      :alt="nickname"
      class="avatar-image"
      @error="handleImageError"
    />
    <div v-else class="avatar-placeholder">
      {{ avatarText }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'

interface Props {
  /** 头像URL */
  avatar?: string
  /** 昵称 */
  nickname: string
  /** 尺寸 */
  size?: 'small' | 'medium' | 'large'
}

const props = withDefaults(defineProps<Props>(), {
  size: 'medium'
})

// 图片加载失败标记
const imageError = ref(false)

// 尺寸类名
const sizeClass = computed(() => `avatar-${props.size}`)

// 头像文字（取昵称首字符）
const avatarText = computed(() => {
  if (!props.nickname) return '用'
  return props.nickname.charAt(0).toUpperCase()
})

// 处理图片加载失败
const handleImageError = () => {
  imageError.value = true
}
</script>

<style scoped>
.user-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  flex-shrink: 0;
}

.avatar-small {
  width: 32px;
  height: 32px;
  font-size: 14px;
}

.avatar-medium {
  width: 40px;
  height: 40px;
  font-size: 16px;
}

.avatar-large {
  width: 64px;
  height: 64px;
  font-size: 24px;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
