<script>
  let { user, size = 30 } = $props();
  let initial = $derived(((user?.display_name || user?.email || '?').trim()[0] || '?').toUpperCase());
  let failed = $state(false);
  // Reset if the picture URL changes (or a different user signs in).
  $effect(() => {
    void user?.avatar_url;
    failed = false;
  });
</script>

{#if user?.avatar_url && !failed}
  <img
    class="av"
    src={user.avatar_url}
    alt=""
    referrerpolicy="no-referrer"
    style="width:{size}px;height:{size}px"
    onerror={() => (failed = true)}
  />
{:else}
  <span class="av init" style="width:{size}px;height:{size}px;font-size:{size * 0.42}px">{initial}</span>
{/if}

<style>
  .av {
    border-radius: 999px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    object-fit: cover;
    flex: none;
  }
  .init {
    background: var(--accent);
    color: #fff;
    font-weight: 600;
    font-family: var(--label);
    line-height: 1;
  }
</style>
