<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">
	<div class="flex h-24 w-24 shrink-0 items-center justify-center">
		<Avatar src={person.avatar} handle={person.handle} size="size-24" class="p-2" />
	</div>

	<div class="flex min-w-0 flex-1 flex-col gap-2 md:flex-row md:items-center md:justify-between">
		<div class="flex min-h-0 flex-1 flex-col justify-around">
			<a
				href={resolve(`/${person.handle}` as "/")}
				class="max-w-full overflow-hidden font-bold text-ellipsis whitespace-nowrap text-foreground-default hover:underline"
			>
				{person.handle}
			</a>
			{#if person.description}
				<p class="pb-2 text-sm break-words text-foreground-muted md:pb-2">{person.description}</p>
			{/if}
			<div
				class="my-2 flex max-w-full items-center gap-2 overflow-hidden text-sm text-ellipsis whitespace-nowrap 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>

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