<script lang="ts">
	import {
		User, Bot, Settings, Eye, EyeOff, Code
	} from 'lucide-svelte';
	import RichText from '$lib/components/RichText.svelte';
	import ChatToolBlock from '$lib/components/ChatToolBlock.svelte';
	import ChatOutsideBlock from '$lib/components/ChatOutsideBlock.svelte';
	import { formatJSON } from '$lib/formatters';
	import {
		splitContent,
		isToolResultBlock,
		isToolUseBlock,
		type OutsideItem
	} from '$lib/chat-utils';
	import type { RequestMessage, ToolResultContentBlock } from '$lib/types';

	interface Props {
		/** The message to render. */
		message: RequestMessage;
		/** Index of this message in the messages array. */
		idx: number;
		/** The full messages array (needed to check next message for "Delivered"). */
		messages: RequestMessage[];
		/** Map of tool_use_id -> tool_result for pairing. */
		toolResultMap: Map<string, ToolResultContentBlock>;
		/** Expanded raw sections state. */
		expandedRawSections: Record<string, boolean>;
		/** Toggle a raw section. */
		onToggleRaw: (key: string) => void;
	}

	let { message, idx, messages, toolResultMap, expandedRawSections, onToggleRaw }: Props = $props();

	let isUser = $derived(message.role === 'user');
	let isAssistant = $derived(message.role === 'assistant');
	let split = $derived(splitContent(message.content));
</script>

<!-- Outside-bubble blocks: everything that isn't plain text -->
{#each split.outside as item, oi}
	{#if isToolResultBlock(item) && item.tool_use_id && toolResultMap.has(item.tool_use_id)}
		<!-- Paired tool result -- already rendered with its tool_use -->
	{:else if isToolUseBlock(item) && item.id && toolResultMap.has(item.id)}
		<ChatToolBlock
			{item}
			result={toolResultMap.get(item.id)}
			rawKey={`out-${idx}-${oi}`}
			{expandedRawSections}
			{onToggleRaw}
		/>
	{:else}
		<ChatOutsideBlock
			{item}
			rawKey={`out-${idx}-${oi}`}
			{expandedRawSections}
			{onToggleRaw}
		/>
	{/if}
{/each}

<!-- Chat bubble -- only plain text content -->
{#if split.chat}
	<div class="flex {isUser ? 'justify-end' : 'justify-start'}">
		<div class="max-w-[85%]">
			<div class="flex items-start space-x-2 {isUser ? 'flex-row-reverse space-x-reverse' : ''}">
				<div class="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center {isUser ? 'bg-blue-100' : isAssistant ? 'bg-gray-100' : 'bg-amber-100'}">
					{#if isUser}
						<User class="w-4 h-4 text-blue-600" />
					{:else if isAssistant}
						<Bot class="w-4 h-4 text-gray-600" />
					{:else}
						<Settings class="w-4 h-4 text-amber-600" />
					{/if}
				</div>
				<div class="min-w-0">
					<div class="{isUser ? 'bg-blue-500 text-white' : isAssistant ? 'bg-gray-200 text-gray-900' : 'bg-amber-50 border border-amber-200 text-gray-900'} rounded-2xl {isUser ? 'rounded-tr-sm' : 'rounded-tl-sm'} px-4 py-3 shadow-sm">
						<RichText text={split.chat} variant={isUser ? 'inverse' : 'default'} />
					</div>
					{#if isUser && idx < messages.length - 1 && messages[idx + 1]?.role === 'assistant'}
						<div class="flex justify-end mt-0.5 px-1">
							<span class="text-[10px] text-gray-400">Delivered</span>
						</div>
					{/if}
				</div>
			</div>
		</div>
	</div>
	<!-- Raw view -- rendered outside the bubble layout so it doesn't resize it -->
	<div class="px-10 {isUser ? 'text-right' : ''}">
		<button
			onclick={() => onToggleRaw(`msg-${idx}`)}
			class="text-[10px] text-gray-400 hover:text-gray-600 inline-flex items-center space-x-1 transition-colors mt-0.5"
		>
			{#if expandedRawSections[`msg-${idx}`]}
				<EyeOff class="w-3 h-3" /><span>Hide raw</span>
			{:else}
				<Eye class="w-3 h-3" /><span>View raw</span>
			{/if}
		</button>
		{#if expandedRawSections[`msg-${idx}`]}
			<pre class="mt-1 text-[10px] bg-gray-900 text-gray-300 rounded-lg p-3 overflow-x-auto max-h-48 font-mono text-left">{formatJSON(message, 0)}</pre>
		{/if}
	</div>
{/if}
