<script>
	import { onMount, afterUpdate } from 'svelte';
	import Composer from '$lib/core/Composer.svelte';

	export let me;

	let messagesContainer;

	const scrollToBottom = () => {
		if (messagesContainer) {
			messagesContainer.scrollTop = messagesContainer.scrollHeight;
		}
	};

	onMount(() => {
		scrollToBottom();
	});

	afterUpdate(() => {
		scrollToBottom();
	});
</script>

{#if $me.store.messages}
	<main bind:this={messagesContainer} class="w-full h-full p-4 overflow-y-auto">
		<div class="grid gap-2">
			{#each $me.store.messages as message}
				<div class="p-4 space-y-2 rounded-tl-none card variant-soft">
					<header class="flex items-center justify-between">
						<p class="font-bold">{message.type} | {message.sender}</p>
						<small class="opacity-50">{message.timestamp}</small>
					</header>
					<p>{message.text}</p>
				</div>
				{#if message.composite}
					<div class="overflow-y-auto max-h-80vh">
						<Composer composer={message.composite} />
					</div>
				{/if}
			{/each}
		</div>
	</main>
{:else}
	<div>Loading...</div>
{/if}
