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

	interface Props {
		tool: ToolCall;
		result?: unknown;
		isStreaming?: boolean;
	}

	let { tool, result, isStreaming = false }: Props = $props();

	// Format tool name for display
	let displayName = $derived(
		tool.name
			.replace(/_/g, ' ')
			.replace(/\b\w/g, (l) => l.toUpperCase())
	);

	// Determine if this is a "read" or "write" operation
	let isReadOnly = $derived(
		tool.name.startsWith('get_') ||
			tool.name.startsWith('list_') ||
			tool.name.includes('_my_')
	);

	let iconColor = $derived(isReadOnly ? 'text-blue-500' : 'text-amber-500');
</script>

<div
	class="rounded-lg border border-gray-200 bg-white p-2 text-sm dark:border-gray-600 dark:bg-gray-800"
>
	<div class="flex items-center gap-2">
		<!-- Tool icon -->
		{#if isStreaming}
			<svg class="h-4 w-4 animate-spin text-gray-400" fill="none" viewBox="0 0 24 24">
				<circle
					class="opacity-25"
					cx="12"
					cy="12"
					r="10"
					stroke="currentColor"
					stroke-width="4"
				></circle>
				<path
					class="opacity-75"
					fill="currentColor"
					d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
				></path>
			</svg>
		{:else}
			<svg class="h-4 w-4 {iconColor}" fill="none" viewBox="0 0 24 24" stroke="currentColor">
				{#if isReadOnly}
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				{:else}
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
					/>
				{/if}
			</svg>
		{/if}

		<span class="font-medium text-gray-700 dark:text-gray-300">{displayName}</span>
	</div>

	<!-- Show result summary if available -->
	{#if result && !isStreaming}
		<div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
			{#if typeof result === 'object' && result !== null}
				{#if Array.isArray(result)}
					{result.length} result{result.length !== 1 ? 's' : ''}
				{:else if 'error' in (result as Record<string, unknown>)}
					<span class="text-red-500">Error: {(result as Record<string, unknown>).error}</span>
				{:else}
					Completed
				{/if}
			{:else}
				{String(result).substring(0, 100)}
			{/if}
		</div>
	{/if}
</div>
