<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 : null
  })

  const counts = $derived.by(() => {
    if (!rows) return null
    const m: Record<string, number> = {}
    for (const r of rows as any[]) m[r.health || 'unknown'] = (m[r.health || 'unknown'] || 0) + 1
    return m
  })

  const loading = $derived(tool.type === 'tool_use')
  const error = $derived(tool.type === 'tool_result' ? tool.error : undefined)
  const total = $derived(counts ? Object.values(counts).reduce((a, b) => a + b, 0) : 0)

  const bars: { label: string; count: number; color: string }[] = [
    { label: 'healthy', count: counts?.healthy ?? 0, color: 'var(--success)' },
    { label: 'degraded', count: counts?.degraded ?? 0, color: 'var(--warning)' },
    { label: 'down', count: counts?.down ?? 0, color: 'var(--destructive)' },
    { label: 'unknown', count: counts?.unknown ?? 0, color: '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 health summary">
    <LoaderCircleIcon class="size-3 shrink-0 animate-spin text-primary" aria-hidden="true" />
    <span class="font-medium">Health summary</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 health summary">
    <XIcon class="size-3 shrink-0 text-destructive" aria-hidden="true" />
    <span class="font-medium">Health summary</span>
    <span class="text-destructive">{error}</span>
  </div>
{:else if counts && total > 0}
  <div class="rounded-lg border bg-card px-3 py-2 text-xs" aria-label="Health summary: {total} entities — healthy {counts?.healthy ?? 0}, degraded {counts?.degraded ?? 0}, down {counts?.down ?? 0}">
    <div class="flex items-center gap-2 mb-1.5">
      <CheckIcon class="size-3 shrink-0 text-success" aria-hidden="true" />
      <span class="font-medium">{total} entities</span>
    </div>
    <div class="flex h-5 w-full overflow-hidden rounded">
      {#each bars as bar}
        {#if bar.count > 0}
          <div
            style="width: {(bar.count / total) * 100}%; background: {bar.color}"
            class="flex items-center justify-center text-[9px] font-medium text-white min-w-[2rem]"
            title="{bar.label}: {bar.count}"
          >
            {bar.count}
          </div>
        {/if}
      {/each}
    </div>
    <div class="mt-1.5 flex flex-wrap gap-x-3 text-muted-foreground">
      {#each bars as bar}
        {#if bar.count > 0}
          <span class="flex items-center gap-1">
            <span class="size-1.5 rounded-full" style="background: {bar.color}"></span>
            {bar.label} {bar.count}
          </span>
        {/if}
      {/each}
    </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="Health summary: no data">
    <CheckIcon class="size-3 shrink-0 text-success" aria-hidden="true" />
    <span class="font-medium">Health summary</span>
    <span class="text-muted-foreground">no data</span>
  </div>
{/if}
