<template>
    <v-avatar :color="getColor(name || id)" :size="size">
        <v-img v-if="imageSrc" alt="John" :src="imageUrl" />
        <span v-else :style="{
            fontSize: `${fontSize}px`,
            lineHeight: `${size}px`
        }">{{ initials }}</span>
    </v-avatar>
</template>

<script setup lang="ts">
const props = defineProps({
    name: {
        type: String,
        default: ""
    },
    color: {
        type: String,
        default: 'red'
    },
    size: {
        type: Number,
        default: 40
    },
    id: {
        type: String, //fallback for constant default color without name
        default: ""
    },
    imageSrc:{
        type: String,
        default: ""
    }

})


const { getNameInitials } = useUtils(); 
const { getFileUrl } = useFile();

const initials = computed(() => {
    return getNameInitials(props.name)
})

const fontSize = computed(() => Math.round(props.size * 0.5))

function getColor(str?: string): string {
    if(!str) return "grey"

    let hash = 0
    for (let i = 0; i < str.length; i++) {
        hash = (hash << 5) - hash + str.charCodeAt(i)
        hash |= 0 // Convert to 32-bit integer
    }

    const hue = Math.abs(hash) % 360
    const saturation = 60 + (Math.abs((hash >> 3) % 20)) // 60–80%
    const lightness = 45 + (Math.abs((hash >> 5) % 15)) // 45–60%

    return `hsl(${hue}, ${saturation}%, ${lightness}%)`
}

const imageUrl = computed(() => {
    return getFileUrl(props?.imageSrc || '')
})

</script>

<style scoped></style>