<script lang="ts">
	import { chat } from '$lib/stores/chat.svelte';
	import Message from './Message.svelte';
	import ToolCallCard from './ToolCallCard.svelte';

	let messagesContainer: HTMLDivElement;

	// Auto-scroll to bottom when new messages arrive
	$effect(() => {
		// Track these to trigger the effect
		const _ = chat.messages.length;
		const __ = chat.streamingContent;

		if (messagesContainer) {
			messagesContainer.scrollTop = messagesContainer.scrollHeight;
		}
	});
</script>

<div bind:this={messagesContainer} class="flex-1 space-y-4 overflow-y-auto p-4">
	{#if chat.messages.length === 0 && !chat.isStreaming}
		<!-- Intro message or empty state -->
		{#if chat.introMessage}
			<div class="flex justify-start">
				<div class="max-w-[85%] rounded-2xl bg-gray-100 px-4 py-3 dark:bg-gray-700">
					<div class="prose prose-sm max-w-none dark:prose-invert">
						{@html chat.introMessage
							.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
							.replace(/^• /gm, '<span class="mr-1">•</span>')
							.replace(/\n\n/g, '</p><p class="mt-2">')
							.replace(/\n/g, '<br>')}
					</div>
				</div>
			</div>
		{:else}
			<div class="flex h-full flex-col items-center justify-center text-center text-gray-500">
				<svg class="mb-4 h-12 w-12 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
					/>
				</svg>
				<p class="text-sm">Connecting to your AI assistant...</p>
			</div>
		{/if}
	{:else}
		<!-- Messages -->
		{#each chat.messages as message (message.id)}
			<Message {message} />
		{/each}

		<!-- Streaming content -->
		{#if chat.isStreaming}
			<div class="flex justify-start">
				<div class="max-w-[85%] rounded-2xl bg-gray-100 px-4 py-2 dark:bg-gray-700">
					<!-- Active tool calls -->
					{#if chat.currentToolCalls.length > 0}
						<div class="mb-2 space-y-2">
							{#each chat.currentToolCalls as tool}
								<ToolCallCard {tool} isStreaming />
							{/each}
						</div>
					{/if}

					<!-- Streaming text -->
					{#if chat.streamingContent}
						<div class="prose prose-sm max-w-none dark:prose-invert">
							{@html chat.streamingContent.replace(/\n/g, '<br>')}
						</div>
					{:else if chat.currentToolCalls.length === 0}
						<!-- Typing indicator -->
						<div class="flex space-x-1">
							<div
								class="h-2 w-2 animate-bounce rounded-full bg-gray-400"
								style="animation-delay: 0ms"
							></div>
							<div
								class="h-2 w-2 animate-bounce rounded-full bg-gray-400"
								style="animation-delay: 150ms"
							></div>
							<div
								class="h-2 w-2 animate-bounce rounded-full bg-gray-400"
								style="animation-delay: 300ms"
							></div>
						</div>
					{/if}
				</div>
			</div>
		{/if}
	{/if}
</div>
