<template lang="pug">
component(
	:is="tag"
	:class="!isPictureOrVideoTag ? 'object-cover' : ''"
)
	source(
		:data-srcset="source.srcsetStr"
		:media="source.media"
		:type="source.type"
		v-for="source in sourcesWithSrcsetStr"
		v-if="isPictureOrVideoTag"
	)
	img.w-full.object-cover.js-lazysizes(
		data-sizes="auto"
		:data-src="src"
		:alt="alt"
		v-if="isPictureOrVideoTag"
	)
</template>

<script>
import '@/utils/lazysizes'
export default {
	props: {
		/** tag of the component */
		tag: {
			type: String,
			default: 'picture',
		},
		/** src attribute of the component or for picture, it's the initial image */
		src: {
			type: String,
			default: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
		},
		/** Array\<_Source_\> that will be rendered as attributes on <source>
		 *
		 * ---
		 *
		 * _Source_ object properties:
		 *
		 * `srcset` (Array\<_Srcset_\>) - srcset attribute for source
		 * `type` (string) - MIME type for the source
		 * `media` (string) - media query
		 *  ----
		 *
		 *
		 * _Srcset_ object properties:
		 *
		 * `src`: the image url for the sourceset, e.g. https://placehold.it/500x500
		 *
		 * `descriptor`: descriptor of the sourceset, e.g. 500w
		 */
		sources: {
			type: Array,
			default: undefined,
		},
		/** alt attribute */
		alt: {
			type: String,
			default: '',
		},
	},
	computed: {
		isPictureOrVideoTag() {
			const { tag } = this
			return tag == 'picture' || tag == 'video'
		},
		sourcesWithSrcsetStr() {
			return this.sources.map(source => ({
				...source,
				srcsetStr: source.srcset
					.map(srcset => ({
						...srcset,
						srcsetStr: `${srcset.src} ${srcset.descriptor}`.trim(),
					}))
					.map(item => item.srcsetStr)
					.join(','),
			}))
		},
	},
}
</script>

<docs>
```jsx
<BaseImg
	:sources="[
		{
			srcset: [
				{
					src: 'https://placehold.it/500x50',
					descriptor: '500w'
				},
				{
					src: 'https://placehold.it/900x90',
					descriptor: '900w'
				}
			],
			type: 'image/jpeg'
		},
		{
			srcset: [
				{
					src: 'https://placehold.it/500x50?ext=webp',
					descriptor: '500w'
				},
				{
					src: 'https://placehold.it/900x90?ext=webp',
					descriptor: '900w'
				}
			],
			type: 'image/webp'
		}
	]"
	src="https://placehold.it/400x400"
/>
```
</docs>
