<template>
  <v-chip
    v-if="user?._source"
    size="small"
    :color="user ? user._source.color || 'grey' : 'grey'"
  >
    <v-avatar start color="indigo">
      <v-img v-if="user._source.avatar" :src="user._source.avatar.file" />
      <span v-else>
        {{ userInitials }}
      </span>
    </v-avatar>
    <span v-if="!props.compact"> {{ displayName }}</span>
  </v-chip>
</template>

<script setup lang="ts">
import useStateSubscriber from "@racletteOrchestrator/composables/useStateSubscriber"
import { computed } from "vue"
import { getValueFromNestedAttributeString } from "@racletteCore/lib/dataHelper"

const props = withDefaults(
  defineProps<{
    userId: string
    compact?: boolean
    attribute?: string
  }>(),
  {
    compact: false,
    attribute: "_displayName",
  },
)

const { state: user } = useStateSubscriber(["data", props.userId])

const userInitials = computed(() => {
  const firstnameInitial = user.value?._source?.firstname?.substring(0, 1)
  const lastnameInitial = user.value?._source?.lastname?.substring(0, 1)

  return `${firstnameInitial}${lastnameInitial}`
})

const displayName = computed(() =>
  getValueFromNestedAttributeString(props.attribute, user.value),
)
</script>
