<script>
	import { messages, createMessage } from '$lib/services/messages';
	import { onMount, afterUpdate } from 'svelte';

	let latestMessages = [];

	messages.subscribe((value) => {
		latestMessages = value;
	});

	let messagesContainer;

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

	onMount(scrollToBottom);
	afterUpdate(scrollToBottom);
</script>

<main bind:this={messagesContainer} class="p-4 overflow-y-auto h-full w-full">
	{#each latestMessages as message}
		<div class="bg-white p-3 rounded-lg shadow-lg mb-2 border-b border-gray-300">
			<div class="flex items-center justify-between">
				<p class="text-sm text-gray-600">
					{message.type} | {message.sender}
				</p>
				<p class="text-xs text-gray-600">{message.timestamp}</p>
			</div>
			<p class="text-base text-gray-800 mt-2">{message.text}</p>
		</div>
	{/each}
</main>
