<script lang="ts">
  let {
    source,
    alternative,
    fallback,
    maxReplaceCount = 1,
    replaceDelay = 1000,
    error = 'https://i2.kym-cdn.com/photos/images/newsfeed/000/290/992/0aa.jpg',
    hideOnError = false,
    style = ''
  }: {
    source: string | undefined | null;
    alternative: string | undefined | null;
    fallback: string | undefined | null;
    maxReplaceCount?: number;
    replaceDelay?: number;
    error?: string;
    hideOnError?: boolean;
    style?: string;
  } = $props();
  let replaceCount = $state(0);

  const delayedReplace = (event: Event, image: string | undefined | null) => {
    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"
    onerror={(e) => delayedReplace(e, fallback)}
    {style}
  />
{:else if !hideOnError}
  <img src={error} alt="Not found" loading="lazy" class="badge" />
{/if}

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