<script lang="ts">
	import UserRound from "$icon/user-round";
	import { avatarUrl } from "$lib/avatar";

	interface Props {
		did?: string;
		src?: string;
		handle?: string;
		tiny?: boolean;
		size?: string;
		class?: string;
	}

	let { did, src, handle, tiny = false, size = "size-10", class: className = "" }: Props = $props();

	const source = $derived(src ?? (did ? avatarUrl(did, tiny) : undefined));

	// an unconfigured avatar service 404s, same as a broken image
	let failed = $state(false);

	$effect(() => {
		if (source) failed = false;
	});
</script>

{#if source && !failed}
	<img
		src={source}
		alt={handle ? `${handle}'s avatar` : "avatar"}
		class={`${size} shrink-0 rounded-full border border-border-default object-cover ${className}`}
		onerror={() => (failed = true)}
	/>
{:else}
	<span
		class={`${size} flex shrink-0 items-center justify-center rounded-full border border-border-default bg-background-inset text-foreground-subtle ${className}`}
		role={handle ? "img" : undefined}
		aria-label={handle ? `${handle}'s avatar` : undefined}
		aria-hidden={handle ? undefined : "true"}
	>
		<UserRound class="size-1/2" />
	</span>
{/if}
