<script lang="ts">
	import { resolve } from "$app/paths";
	import Avatar from "$lib/components/ui/Avatar.svelte";
	import Users from "$icon/users";
	import FollowButton from "./FollowButton.svelte";
	import type { FollowChange, PersonData } from "./types";
	import { createOptimisticCount } from "$lib/optimistic.svelte";

	let { person }: { person: PersonData } = $props();

	const followerCount = createOptimisticCount({
		key: () => person.did,
		loaded: () => person.followers
	});

	const followed = (change: FollowChange) => followerCount.adjust(change.delta);
</script>

<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
	<div class="flex min-w-0 flex-1 items-center gap-4">
		<div class="flex size-24 shrink-0 items-center justify-center">
			<Avatar did={person.did} handle={person.handle} size="full" class="p-2" />
		</div>

		<div class="flex min-w-0 flex-1 flex-col justify-around">
			<a
				href={resolve(`/${person.handle}` as "/")}
				class="max-w-full truncate font-bold text-foreground-default hover:underline"
			>
				{person.handle}
			</a>
			{#if person.description}
				<p class="pb-2 typography-paragraph-small wrap-break-word text-foreground-muted md:pb-2">
					{person.description}
				</p>
			{/if}
			<div class="my-2 flex max-w-full items-center gap-2 truncate typography-paragraph-small text-foreground-subtle">
				<Users class="size-4 shrink-0" />
				<span
					><a
						href={resolve(`/${person.handle}?tab=followers` as "/")}
						class="hover:text-foreground-default hover:underline">{followerCount.value} followers</a
					></span
				>
				<span class="select-none after:content-['·']"></span>
				<span
					><a
						href={resolve(`/${person.handle}?tab=following` as "/")}
						class="hover:text-foreground-default hover:underline">{person.following} following</a
					></span
				>
			</div>
		</div>
	</div>

	{#if !person.isSelf}
		<div class="w-full md:w-auto md:max-w-32">
			<FollowButton
				profileDid={person.did}
				initialRkey={person.viewerFollowRkey}
				onCommit={followed}
			/>
		</div>
	{/if}
</div>
