<script lang="ts">
  import type { ToolCallResult } from '$lib/stores/chat'
  import * as Collapsible from '$lib/components/ui/collapsible'
  import CheckIcon from '@lucide/svelte/icons/check'
  import XIcon from '@lucide/svelte/icons/x'
  import ChevronDownIcon from '@lucide/svelte/icons/chevron-down'
  import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle'

  let { tools, unmatched, active = false }: { tools: ToolCallResult[]; unmatched?: ToolCallResult[]; active?: boolean } = $props()

  let open = $state(false)
  let wasActive = $state(active)

  const bodyTools = $derived(unmatched ?? tools)
  const inlineCount = $derived(tools.length - bodyTools.length)

  $effect(() => {
    if (active && !wasActive) open = true
    if (!active && wasActive) open = false
    wasActive = active
  })

  const doneCount = $derived(bodyTools.filter((t) => t.type === 'tool_result').length)
  const hasError = $derived(bodyTools.some((t) => t.type === 'tool_result' && t.error))
  const total = $derived(bodyTools.length)

  const runningTool = $derived(
    active ? bodyTools.find((t) => t.type === 'tool_use') : undefined
  )

  function toolLabel(t: ToolCallResult): string {
    if (!t.args || typeof t.args !== 'object') return t.name
    const firstArg = Object.values(t.args as Record<string, unknown>)[0]
    if (typeof firstArg === 'string' && firstArg.length < 50) return `${t.name} ${firstArg}`
    return t.name
  }
</script>

{#if bodyTools.length}
  <Collapsible.Root bind:open class="group w-fit max-w-full overflow-hidden rounded border bg-card/50 text-xs">
    <Collapsible.Trigger class="flex w-full cursor-pointer select-none items-center gap-1.5 px-2 py-1 hover:bg-muted/30">
      <span class="shrink-0">
        {#if active && doneCount < total}
          <LoaderCircleIcon class="size-3 animate-spin text-primary" aria-hidden="true" />
        {:else if hasError}
          <XIcon class="size-3 text-destructive" aria-hidden="true" />
        {:else}
          <CheckIcon class="size-3 text-muted-foreground" aria-hidden="true" />
        {/if}
      </span>

      <span class="text-muted-foreground">
        {#if active && doneCount < total}
          {doneCount}/{total}
        {:else}
          {total} tool{total === 1 ? '' : 's'}
        {/if}
        {#if inlineCount > 0}
          <span> · {inlineCount} inline</span>
        {/if}
      </span>

      {#if active && runningTool}
        <span class="font-mono truncate">{toolLabel(runningTool)}<span class="animate-pulse">…</span></span>
      {/if}

      <ChevronDownIcon
        class="size-3 shrink-0 text-muted-foreground transition-transform duration-200 ml-auto {open ? 'rotate-180' : ''}"
        aria-hidden="true"
      />
    </Collapsible.Trigger>

    <Collapsible.Content class="overflow-hidden transition-all duration-200 ease-out data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=closed]:slide-out-to-top-1 data-[state=open]:animate-in data-[state=open]:fade-in data-[state=open]:slide-in-from-top-1">
      <div class="flex flex-col divide-y border-t px-2 py-1">
        {#each bodyTools as tool (tool.id)}
          <div class="flex items-center gap-1.5 py-0.5">
            {#if tool.type === 'tool_result' && tool.error}
              <XIcon class="size-3 shrink-0 text-destructive" />
            {:else if tool.type === 'tool_result'}
              <CheckIcon class="size-3 shrink-0 text-success" />
            {:else}
              <LoaderCircleIcon class="size-3 shrink-0 animate-spin text-primary" />
            {/if}
            <span class="font-mono text-[11px] truncate">{toolLabel(tool)}</span>
          </div>
        {/each}
      </div>
    </Collapsible.Content>
  </Collapsible.Root>
{/if}
