<script lang="ts">
  import { onMount } from 'svelte'
  import {
    startWorkspace,
    touched,
    healthDiffs,
    workspaceFor,
    taskFor,
    taskWorking,
    currentWorking,
    currentTask
  } from '$lib/stores/workspace'
  import { messages, chatFor, streaming, connectionState } from '$lib/stores/chat'
  import SessionGraph from './SessionGraph.svelte'

  let { sessionId = null }: { sessionId?: string | null } = $props()

  onMount(() => (sessionId ? undefined : startWorkspace()))

  const ws = $derived(sessionId ? workspaceFor(sessionId) : null)
  const touchedStore = $derived(ws ? ws.touched : touched)
  const healthDiffsStore = $derived(ws ? ws.healthDiffs : healthDiffs)
  const chat = $derived(sessionId ? chatFor(sessionId) : null)
  const messagesStore = $derived(chat ? chat.messages : messages)

  // eslint-disable-next-line svelte/valid-compile
  const taskWorkingStore = sessionId ? taskWorking(sessionId) : currentWorking
  // eslint-disable-next-line svelte/valid-compile
  const taskStreamingStore = sessionId ? chatFor(sessionId).streaming : streaming
  // eslint-disable-next-line svelte/valid-compile
  const taskConnStore = sessionId ? chatFor(sessionId).connectionState : connectionState
  // eslint-disable-next-line svelte/valid-compile
  const taskStatusStore = sessionId ? taskFor(sessionId) : currentTask

  // ── stuck detection (mirrors ChatThread) ───────────────────────────────
  let now = $state(Date.now())
  $effect(() => {
    if (!$taskWorkingStore) return
    const id = setInterval(() => {
      now = Date.now()
    }, 1000)
    return () => clearInterval(id)
  })
  const lastActiveAt = $derived($taskStatusStore?.last_active_at)
  const isStuck = $derived(
    $taskWorkingStore &&
      !$taskStreamingStore &&
      lastActiveAt &&
      now - new Date(lastActiveAt).getTime() > 300_000
  )

</script>

<div class="flex h-full min-h-0 flex-col">
  <div class="shrink-0" style="aspect-ratio: 1; width: 100%;">
    <SessionGraph
      messages={$messagesStore}
      touched={$touchedStore}
      healthDiffs={$healthDiffsStore}
    />
  </div>
</div>

<style>
</style>