<script lang="ts">
	export let source: string | undefined;
	export let alternative: string | undefined;
	export let fallback: string | undefined;
	export let maxReplaceCount = 1;
	export let replaceDelay = 1000;
	export let error = 'https://i2.kym-cdn.com/photos/images/newsfeed/000/290/992/0aa.jpg';

	let replaceCount = 0;

	const delayedReplace = (event: Event, image: string | undefined) => {
		if (replaceCount >= maxReplaceCount) return;

		setTimeout(() => {
			(event.target as HTMLImageElement).src = image || '';

			replaceCount += 1;
		}, replaceDelay);
	};
</script>

{#if replaceCount < maxReplaceCount}
	<img
		src={source}
		alt={alternative}
		loading="lazy"
		class="badge"
		on:error={(e) => delayedReplace(e, fallback)}
	/>
{:else}
	<img src={error} alt="Not found" loading="lazy" class="badge" />
{/if}

<style>
	.badge {
		border-radius: 8px;
	}
</style>
