<template>
  <div class="message-attachments">
    <template v-for="item in media" :key="item.id">
      <a
        v-if="isImage(item)"
        :href="item.url"
        target="_blank"
        rel="noopener"
        class="message-attachments__image-link"
      >
        <img :src="item.url" :alt="item.fileName" class="message-attachments__image" />
      </a>
      <a
        v-else
        :href="item.downloadUrl || item.url"
        target="_blank"
        rel="noopener"
        class="message-attachments__file"
      >
        <SvgIcon name="file" :size="18" color="currentColor" />
        <span class="message-attachments__name">{{ item.fileName }}</span>
        <span class="message-attachments__size">{{ formatFileSize(item.fileSize) }}</span>
      </a>
    </template>
  </div>
</template>

<script setup>
import SvgIcon from '@/components/icons/SvgIcon.vue'

defineProps({
  media: { type: Array, default: () => [] },
})

const isImage = (item) =>
  (item.mimeType || '').startsWith('image/') || /\.(jpe?g|png|gif|webp)$/i.test(item.fileName || '')

const formatFileSize = (bytes) => {
  if (!bytes) return ''
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}
</script>

<style lang="scss" scoped>
.message-attachments {
  display: flex;
  flex-direction: column;
  gap: 0.375rem;
  margin-bottom: 0.375rem;

  &__image-link {
    display: block;
    max-width: 16rem;
  }

  &__image {
    display: block;
    width: 100%;
    max-height: 12rem;
    object-fit: cover;
    border-radius: 0.625rem;
  }

  &__file {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.375rem 0.625rem;
    border-radius: 0.625rem;
    background: rgba(0, 0, 0, 8%);
    color: inherit;
    text-decoration: none;
    max-width: 100%;

    &:hover {
      background: rgba(0, 0, 0, 14%);
    }
  }

  &__name {
    font-family: var(--font-family-fa);
    font-size: 0.75rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    min-width: 0;
  }

  &__size {
    font-family: var(--font-family-en);
    font-size: 0.65rem;
    opacity: 0.75;
    white-space: nowrap;
  }
}
</style>
