<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 loading = $derived(tool.type === 'tool_use')
  const error = $derived(tool.type === 'tool_result' ? tool.error : undefined)

  function shortTs(ts: string): string {
    try {
      const d = new Date(ts)
      return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
    } catch {
      return ts?.slice(11, 19) ?? ''
    }
  }

  function shortDate(ts: string): string {
    return ts?.slice(0, 10) ?? ''
  }

  function shortId(id: string): string {
    if (!id) return ''
    return id.length > 12 ? id.slice(0, 12) : id
  }

  const activityRows = $derived.by(() => {
    if (!rows) return null
    return rows.map((r) => ({
      time: shortTs(r.timestamp || r.ts || ''),
      date: shortDate(r.timestamp || r.ts || ''),
      actor: r.actor_label || shortId(r.agent_id) || r.actor_type || '',
      action: r.action || r.activity_type || '',
      toolName: r.tool_name || r.path || '',
      status: r.success ?? (r.error ? 'false' : undefined),
    }))
  })
</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 activity log">
    <LoaderCircleIcon class="size-3 shrink-0 animate-spin text-primary" aria-hidden="true" />
    <span class="font-medium">Activity log</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="Activity log error">
    <XIcon class="size-3 shrink-0 text-destructive" aria-hidden="true" />
    <span class="font-medium">Activity log</span>
    <span class="text-destructive">{error}</span>
  </div>
{:else if activityRows && activityRows.length > 0}
  <div class="rounded-lg border bg-card text-xs" aria-label="Activity log: {activityRows.length} entries">
    <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">{activityRows.length} entr{activityRows.length === 1 ? 'y' : 'ies'}</span>
    </div>
    <div class="max-h-56 overflow-y-auto divide-y">
      {#each activityRows as row}
        <div class="flex items-center gap-2 px-3 py-1.5 font-mono">
          <span class="shrink-0 text-muted-foreground">{row.time}</span>
          {#if row.date !== activityRows[0].date}
            <span class="shrink-0 text-[10px] text-muted-foreground/60">{row.date}</span>
          {/if}
          <span class="text-muted-foreground">{row.action}</span>
          <span class="max-w-32 truncate">{row.toolName}</span>
          <span class="text-muted-foreground/60">{row.actor}</span>
          {#if row.status === 'true'}
            <span class="ml-auto size-1.5 shrink-0 rounded-full bg-success" title="success"></span>
          {:else if row.status === 'false'}
            <span class="ml-auto size-1.5 shrink-0 rounded-full bg-destructive" title="error"></span>
          {/if}
        </div>
      {/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="Activity log: no entries">
    <CheckIcon class="size-3 shrink-0 text-success" aria-hidden="true" />
    <span class="font-medium">Activity log</span>
    <span class="text-muted-foreground">no entries</span>
  </div>
{/if}
