<script lang="ts">
	import { type PartialLetter, partialLetterStatus } from '$lib/letterHandler.svelte';
	import { slide } from 'svelte/transition';
	import Icon from '@iconify/svelte';
	import { getReadableDate, getReadableTime } from '$lib/utils.svelte';
	import type { FolderLabel } from '$lib/folderLabel';
	import NostrIdentifier from './NostrIdentifier.svelte';
	import { goto } from '$app/navigation';

	let {
		partialLetter,
		activeFolder,
		selected = false,
		onSelection = null
	} = $props<{
		partialLetter: PartialLetter;
		activeFolder: FolderLabel;
		selected?: boolean;
		onSelection?: (() => void) | null;
	}>();

	function linkClicked() {
		if (!onSelection) return goto('/letters/' + partialLetter.id);
		onSelection();
		return false;
	}
</script>

<span class="letter-item" class:selected in:slide onclick={linkClicked} out:slide>
	{#if partialLetter.status === partialLetterStatus.CONTENT_LOADED}
		Loading...
	{:else}
		{@const letter = partialLetter.event}
		<div class="subject-line">
			<div class="letter-subject">
				{#if !letter.emailAddress}
					<img src="/nostr-lock.svg" width="32" />
				{/if}
				{letter.subject}
			</div>
			{#if letter.stamp}
				<div class="stamps-count">
					<Icon icon="fxemoji:stampedenvelope" />
					{letter.stamp.amount} sats
				</div>
			{/if}
		</div>
		<div class="letter-from">
			{#if activeFolder.id === 'sent'}
				{#each letter.recipients as recipient}
					<NostrIdentifier user={recipient.npub} />
				{/each}
			{:else if letter.from}
				<NostrIdentifier user={letter.from.npub} emailAddress={letter.emailAddress} />
			{/if}
		</div>
		<div class="letter-meta">
			<Icon icon="ph:calendar-duotone" />
			{getReadableDate(letter.date)}
			&nbsp;
			<Icon icon="ph:clock-duotone" />
			{getReadableTime(letter.date)}
		</div>
	{/if}
</span>
