<script lang="ts">
  import type { ToolCallResult } from '$lib/stores/chat'
  import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle'
  import CheckIcon from '@lucide/svelte/icons/check'
  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 summary = $derived.by(() => {
    if (!rows) return null
    const health: Record<string, number> = {}
    const types: Record<string, number> = {}
    for (const r of rows) {
      health[r.health || 'unknown'] = (health[r.health || 'unknown'] || 0) + 1
      types[r.type || 'unknown'] = (types[r.type || 'unknown'] || 0) + 1
    }
    return { health, types, total: rows.length }
  })

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

  const healthColor: Record<string, string> = {
    healthy: 'var(--success)',
    degraded: 'var(--warning)',
    down: 'var(--destructive)',
    unknown: 'var(--muted-foreground)',
  }
</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 fleet snapshot">
    <LoaderCircleIcon class="size-3 shrink-0 animate-spin text-primary" aria-hidden="true" />
    <span class="font-medium">Fleet snapshot</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="Fleet snapshot error">
    <XIcon class="size-3 shrink-0 text-destructive" aria-hidden="true" />
    <span class="font-medium">Fleet snapshot</span>
    <span class="text-destructive">{error}</span>
  </div>
{:else if summary && summary.total > 0}
  <div class="rounded-lg border bg-card text-xs" aria-label="Fleet snapshot: {summary.total} entities">
    <div class="flex items-center gap-2 px-3 py-1.5 border-b">
      <CheckIcon class="size-3 shrink-0 text-success" aria-hidden="true" />
      <span class="font-medium">{summary.total} entities</span>
    </div>
    <div class="px-3 py-2 space-y-2">
      <!-- Health -->
      <div>
        <div class="text-muted-foreground mb-1">Health</div>
        <div class="grid grid-cols-2 gap-x-3 gap-y-1">
          {#each ['healthy', 'degraded', 'down', 'unknown'] as h}
            {#if summary.health[h]}
              <div class="flex items-center gap-1.5 font-mono">
                <span class="size-1.5 rounded-full" style="background: {healthColor[h] ?? 'var(--muted-foreground)'}"></span>
                <span class="text-muted-foreground">{h}</span>
                <span class="tabular-nums">{summary.health[h]}</span>
              </div>
            {/if}
          {/each}
        </div>
      </div>
      <!-- Types -->
      {#if Object.keys(summary.types).length > 0}
        <div>
          <div class="text-muted-foreground mb-1">By type</div>
          <div class="grid grid-cols-2 gap-x-3 gap-y-1">
            {#each Object.entries(summary.types).sort(([,a], [,b]) => b - a) as [type, count]}
              <div class="flex items-center gap-1.5 font-mono">
                <span class="text-muted-foreground">{type}</span>
                <span class="tabular-nums">{count}</span>
              </div>
            {/each}
          </div>
        </div>
      {/if}
    </div>
  </div>
{:else}
  <div class="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 text-xs" role="status" aria-label="Fleet snapshot: no data">
    <CheckIcon class="size-3 shrink-0 text-success" aria-hidden="true" />
    <span class="font-medium">Fleet snapshot</span>
    <span class="text-muted-foreground">no data</span>
  </div>
{/if}
