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

import { defaultAssistantAvatar } from './assistantAvatar';

const props = defineProps<{
  src?: string;
}>();

const imageFailed = ref(false);
const avatarSrc = computed(() => {
  const source = props.src?.trim();
  return imageFailed.value || !source ? defaultAssistantAvatar : source;
});

watch(
  () => props.src,
  () => {
    imageFailed.value = false;
  },
);

function handleImageError() {
  if (avatarSrc.value !== defaultAssistantAvatar) {
    imageFailed.value = true;
  }
}
</script>

<template>
  <span class="chat-assistant-avatar" aria-hidden="true">
    <img :src="avatarSrc" alt="" @error="handleImageError" />
  </span>
</template>

<style scoped>
.chat-assistant-avatar,
.chat-assistant-avatar img {
  display: block;
  width: 100%;
  height: 100%;
}

.chat-assistant-avatar {
  overflow: hidden;
  border-radius: inherit;
}

.chat-assistant-avatar img {
  object-fit: cover;
}
</style>
