<script lang="ts">
  import type { ToolCallResult } from '$lib/stores/chat'
  import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle'
  import XIcon from '@lucide/svelte/icons/x'

  let { tool }: { tool: ToolCallResult } = $props()

  const rows = $derived.by(() => {
    if (tool.type !== 'tool_result' || !tool.result) return null
    const data = (tool.result as any).data ?? tool.result
    return Array.isArray(data) ? data as any[] : null
  })

  const loading = $derived(tool.type === 'tool_use')
  const error = $derived(tool.type === 'tool_result' ? tool.error : undefined)

  const cols = $derived(rows && rows.length > 0 ? Object.keys(rows[0]).filter(k => k !== '__renderer') : [])
</script>

{#if loading}
  <div class="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 text-xs" role="status" aria-label="Loading entities">
    <LoaderCircleIcon class="size-3 shrink-0 animate-spin text-primary" aria-hidden="true" />
    <span class="font-medium">Entities</span>
    <span class="animate-pulse text-muted-foreground">loading…</span>
  </div>
{:else if error}
  <div class="flex items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs" role="alert" aria-label="Error loading entities">
    <XIcon class="size-3 shrink-0 text-destructive" aria-hidden="true" />
    <span class="font-medium">Entities</span>
    <span class="text-destructive">{error}</span>
  </div>
{:else if rows && rows.length > 0}
  <div class="rounded-lg border bg-card text-xs" aria-label="Entities: {rows.length} results">
    <div class="max-h-56 overflow-y-auto">
      <table class="w-full">
        <thead>
          <tr class="border-b text-muted-foreground">
            {#each cols as col}
              <th class="px-2 py-1 text-left font-medium whitespace-nowrap">{col}</th>
            {/each}
          </tr>
        </thead>
        <tbody>
          {#each rows as row}
            <tr class="border-b last:border-0 hover:bg-muted/30">
              {#each cols as col}
                <td class="px-2 py-1 whitespace-nowrap font-mono max-w-48 truncate">{row[col] ?? '—'}</td>
              {/each}
            </tr>
          {/each}
        </tbody>
      </table>
    </div>
  </div>
{:else}
  <div class="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 text-xs text-muted-foreground" role="status" aria-label="Entities: no results">
    <XIcon class="size-3 shrink-0" aria-hidden="true" />
    <span>No entities found</span>
  </div>
{/if}
