<script lang="ts">
  import { onMount } from 'svelte'
  import { Pane, Splitpanes } from 'svelte-splitpanes'
  import {
    startWorkspace,
    planSteps,
    currentTask,
    touched,
    healthDiffs,
    workspaceFor,
    taskFor
  } from '$lib/stores/workspace'
  import { streaming, messages, chatFor } from '$lib/stores/chat'
  import { activityLog, activityLogFor } from '$lib/stores/activity'
  import SessionGraph from './SessionGraph.svelte'
  import UnifiedTimeline from './UnifiedTimeline.svelte'
  import ChevronDownIcon from '@lucide/svelte/icons/chevron-down'
  import ChevronRightIcon from '@lucide/svelte/icons/chevron-right'
  import Spinner from './Spinner.svelte'

  // Omitted (main Chat page): tracks the global "current session" — one
  // shared view, same as always. Passed (a floating task window's
  // SessionChatWindow): this panel switches entirely to that session's own
  // store bundle (workspaceFor/chatFor/activityLogFor), so several windows'
  // panels can be open and live at once instead of all showing whatever
  // happens to be the single global "current session". Per-session workspace
  // tracking (startSessionWorkspace) is started by SessionChatWindow itself,
  // not here — it has to run even while this panel stays unmounted (see its
  // hasContext gate), so only the global fallback path starts its own here.
  let { sessionId = null }: { sessionId?: string | null } = $props()

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

  const ws = $derived(sessionId ? workspaceFor(sessionId) : null)
  const planStepsStore = $derived(ws ? ws.planSteps : planSteps)
  const touchedStore = $derived(ws ? ws.touched : touched)
  const healthDiffsStore = $derived(ws ? ws.healthDiffs : healthDiffs)
  const taskStore = $derived(sessionId ? taskFor(sessionId) : currentTask)
  const chat = $derived(sessionId ? chatFor(sessionId) : null)
  const streamingStore = $derived(chat ? chat.streaming : streaming)
  const messagesStore = $derived(chat ? chat.messages : messages)
  const activityLogStore = $derived(sessionId ? activityLogFor(sessionId) : activityLog)

  let scopeOpen = $state(true)
  let activityOpen = $state(true)

  // Resize: each section is a Pane in one vertical Splitpanes. Sizes are
  // percentages of the panel's height; undefined means "share the space
  // evenly with the other auto sections". Collapsing a section pins it to
  // COLLAPSED_SIZE (roughly a header's worth of height) and remembers its
  // last size so reopening restores it.
  const COLLAPSED_SIZE = 6
  const OPEN_MIN_SIZE = 12
  let sizes = $state<(number | undefined)[]>([30, 70])
  // Reopening must restore a concrete number, never `undefined` — the pane
  // only re-triggers the library's resize/equalize pass when `size` changes
  // to a different *number*, so setting it back to `undefined` silently
  // no-ops and leaves the section stuck at its collapsed height.
  let savedSizes: number[] = [30, 70]

  function toggleSection(i: number, isOpen: boolean) {
    if (isOpen) {
      savedSizes[i] = sizes[i] ?? savedSizes[i]
      sizes[i] = COLLAPSED_SIZE
    } else {
      sizes[i] = savedSizes[i]
    }
  }

  // Plan collapsed status
  const planDone = $derived($planStepsStore.filter((s) => s.status === 'done').length)
  const planTotal = $derived($planStepsStore.length)

  // Activity collapsed status
  const activityRunning = $derived($activityLogStore.filter((e) => e.status === 'running').length)
</script>

<div class="flex h-full min-h-0 flex-col">
  <Splitpanes horizontal theme="oikos-theme" dblClickSplitter={false} class="min-h-0 flex-1">
    <!-- Scope -->
    <Pane
      bind:size={sizes[0]}
      minSize={scopeOpen ? OPEN_MIN_SIZE : COLLAPSED_SIZE}
      maxSize={scopeOpen ? 100 : COLLAPSED_SIZE}
      class="flex flex-col"
    >
      <button
        type="button"
        class="flex shrink-0 items-center gap-1.5 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground hover:text-foreground"
        onclick={() => {
          toggleSection(0, scopeOpen)
          scopeOpen = !scopeOpen
        }}
      >
        {#if scopeOpen}<ChevronDownIcon class="size-3" />{:else}<ChevronRightIcon
            class="size-3"
          />{/if}
        <span>Scope</span>
        {#if !scopeOpen}
          <span class="ml-auto font-normal normal-case"
            >{$touchedStore.length
              ? `${$touchedStore.length} entit${$touchedStore.length === 1 ? 'y' : 'ies'}`
              : 'Graph'}</span
          >
        {/if}
      </button>
      {#if scopeOpen}
        <div class="min-h-0 flex-1">
          <SessionGraph
            messages={$messagesStore}
            touched={$touchedStore}
            healthDiffs={$healthDiffsStore}
          />
        </div>
      {/if}
    </Pane>

    <!-- Activity (merged plan + event log) -->
    <Pane
      bind:size={sizes[1]}
      minSize={activityOpen ? OPEN_MIN_SIZE : COLLAPSED_SIZE}
      maxSize={activityOpen ? 100 : COLLAPSED_SIZE}
      class="flex flex-col"
    >
      <button
        type="button"
        class="flex shrink-0 items-center gap-1.5 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground hover:text-foreground"
        onclick={() => {
          toggleSection(1, activityOpen)
          activityOpen = !activityOpen
        }}
      >
        {#if activityOpen}<ChevronDownIcon class="size-3" />{:else}<ChevronRightIcon
            class="size-3"
          />{/if}
        <span>Activity</span>
        {#if $streamingStore && activityRunning > 0}
          <Spinner class="size-3 text-primary" />
        {/if}
        {#if planTotal > 0}
          <span
            class="font-normal normal-case tabular-nums {planDone === planTotal
              ? 'text-muted-foreground'
              : 'text-primary'}">{planDone}/{planTotal}</span
          >
        {/if}
        {#if !activityOpen && planTotal === 0}
          {#if $taskStore?.goal}
            <span class="ml-auto max-w-[120px] truncate font-normal normal-case"
              >{$taskStore.goal}</span
            >
          {:else}
            <span class="ml-auto font-normal normal-case text-muted-foreground"
              >No activity yet</span
            >
          {/if}
        {/if}
      </button>
      {#if activityOpen}
        <div class="min-h-0 flex-1 overflow-hidden">
          <UnifiedTimeline
            entries={$activityLogStore}
            planSteps={$planStepsStore}
            streaming={$streamingStore}
          />
        </div>
      {/if}
    </Pane>
  </Splitpanes>
</div>
