<template>
  <q-avatar
    :square="type==='square'"
    :rounded="type==='rounded'"
    :size="size"
    >
    <img
      v-if="img"
      :src="img"
      style=" object-fit: cover;"
    />
    <div
      v-else
      :style="{ backgroundColor: stringToColour(name) } "
      class="fit flex items-center justify-center text-white"
      > 
      {{ name ? name.substring(0, 1) : '-' }}
    </div>
  </q-avatar>
</template>

<script setup lang="ts">

  interface Props {
    img?: string | null
    name: string,
    size?: string,
    type?: 'rounded' | 'square' | '' 
  }

  withDefaults(defineProps<Props>(), {
    img: null,
    name: '-',
    size: 'md',
    type: ''
  })  

  const stringToColour = (str: string) => {
    if (!str) return '#eee'
    let hash = 0
    str.split('').forEach(char => {
      hash = char.charCodeAt(0) + ((hash << 5) - hash)
    })
    let colour = '#'
    for (let i = 0; i < 3; i++) {
      const value = (hash >> (i * 8)) & 0xff
      colour += value.toString(16).padStart(2, '0')
    }
    return colour
  }

</script>
