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

	export let store;

	let isStoreLoaded = false;

	let messagesContainer;

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

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

	afterUpdate(() => {
		scrollToBottom();
	});
	$: if ($store) isStoreLoaded = true;
</script>

{#if isStoreLoaded}
	{#if $store.messages}
		<main bind:this={messagesContainer} class="w-full h-full p-4 overflow-y-auto">
			<div class="grid gap-2">
				{#each $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">
							<Composite composite={message.composite} />
						</div>
					{/if}
				{/each}
			</div>
		</main>
	{/if}
{:else}
	<div>Loading...</div>
{/if}
