<script>
	import { messages, createMessage } from '$lib/services/messages';
	import { onMount, afterUpdate } from 'svelte';
	import Composite from './Composite.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="w-full h-full p-4 overflow-y-auto">
	{#each latestMessages as message}
		<div class="p-3 mb-2 bg-white border-b border-gray-300 rounded-lg shadow-lg">
			<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="mt-2 text-base text-gray-800">{message.text}</p>
		</div>
		<!-- Render Composite Component -->
		{#if message.composite}
			<div class="overflow-y-auto max-h-80vh">
				<Composite componentsData={message.composite} />
			</div>
		{/if}
	{/each}
</main>
