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

const props = defineProps<{
  name: string
  initials?: string | null
  avatarUrl?: string | null
  /** Taille en px (carré). Défaut 36. */
  size?: number
}>()

const sizePx = computed(() => props.size ?? 36)

const computedInitials = computed(() => {
  if (props.initials && props.initials.length) return props.initials.slice(0, 3).toUpperCase()
  // Fallback : 1re lettre de chaque mot, max 2.
  return props.name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map(w => w[0]?.toUpperCase() ?? '')
    .join('')
    || '?'
})

// Couleur stable par hash du nom -> palette pastel.
const palette = ['#3B82F6', '#EF4444', '#14B8A6', '#F97316', '#22C55E', '#A855F7', '#0EA5E9', '#EAB308']
const color = computed(() => {
  let h = 0
  for (const c of props.name) h = (h * 31 + c.charCodeAt(0)) | 0
  return palette[Math.abs(h) % palette.length]
})
</script>

<template>
  <span
    v-if="avatarUrl"
    class="inline-block rounded-full bg-gray-100 bg-center bg-cover shrink-0"
    :style="{ width: `${sizePx}px`, height: `${sizePx}px`, backgroundImage: `url(${avatarUrl})` }"
    :title="name"
  />
  <span
    v-else
    class="inline-flex items-center justify-center rounded-full font-medium shrink-0"
    :style="{
      width: `${sizePx}px`,
      height: `${sizePx}px`,
      fontSize: `${Math.round(sizePx * 0.4)}px`,
      background: color + '1A',
      color: color,
    }"
    :title="name"
  >
    {{ computedInitials }}
  </span>
</template>
