<template>
  <img
    v-bind="$attrs"
    :src="imgSrc"
    :srcset="srcset"
    :loading="loading"
    :width="width"
    :height="height"
    :sizes="computedSizes"
    :alt="alt"
    :fetchpriority="priority ? 'high' : 'auto'"
    @error="emit('error', $event)"
  >
</template>

<script setup lang="ts">
import type { IThumbUrls } from '../../types';
import { ThumbSize } from '../../runtime';

const props = withDefaults(defineProps<{
  src?: string,
  width: string | number,
  height: string | number,
  sizes?: string,
  urls?: IThumbUrls,
  alt?: string,
  loading?: 'lazy' | 'eager',
  fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside',
  priority?: boolean,
}>(), {
  loading: 'lazy',
  fit: 'cover',
});

const computedSizes = computed(() => {
  if (props.loading === 'lazy') return 'auto';
  return props.sizes;
});

const imgSrc = computed(() => {
  if (props.src) return props.src;
  if (props.urls) return props.urls.webp[ThumbSize.Medium];
  return undefined;
});

const srcset = computed(() => {
  if (!props.urls) return undefined;
  const entries = Object.entries(props.urls.webp);
  if (!entries.length) return undefined;
  return entries
    .map(([size, url]) => `${url} ${size.split('x')[0]}w`)
    .join(', ');
});

const emit = defineEmits<{
  (e: 'error', event: Event): void
}>();
</script>
