<template>
  <div class="flex h-full min-h-0 flex-col">
    <div class="flex items-center gap-1 px-3 py-2 text-[11px] font-semibold tracking-wide text-fg-subtle uppercase">
      {{ t('ide.activity.sessions') }}
      <RouterLink :to="{ name: 'sessions' }" class="ml-auto rounded p-0.5 hover:bg-surface-2 hover:text-fg" :title="t('nav.sessions')">
        <ExternalLink :size="12" />
      </RouterLink>
    </div>
    <div class="min-h-0 flex-1 overflow-auto px-1 pb-2">
      <p v-if="liveSessions.length === 0" class="px-2 py-1 text-xs text-fg-subtle">{{ t('sessions.empty') }}</p>
      <button
        v-for="s in liveSessions"
        :key="s.id"
        type="button"
        class="flex w-full items-center gap-1.5 rounded px-2 py-1 text-left text-xs hover:bg-surface-2/60"
        :class="ide.activeDockSessionId === s.id ? 'bg-surface-2 text-fg' : 'text-fg-muted'"
        @click="ide.openTerminal(s.id)"
      >
        <SessionStateBadge :session="s" />
        <span class="truncate font-mono">{{ titleFor(s) }}</span>
        <span class="ml-auto shrink-0 font-mono text-[10px] text-fg-subtle">{{ s.command }}</span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ExternalLink } from '@lucide/vue';
import type { SessionSummary } from '@arboretum/shared';
import { useIdeStore } from '../../stores/ide';
import { useSessionsStore } from '../../stores/sessions';
import { useWorktreesStore } from '../../stores/worktrees';
import SessionStateBadge from '../SessionStateBadge.vue';

const { t } = useI18n();
const ide = useIdeStore();
const sessions = useSessionsStore();
const worktrees = useWorktreesStore();

const liveSessions = computed(() => sessions.sessions.filter((s) => s.live));

function titleFor(s: SessionSummary): string {
  const wt = worktrees.worktrees.find((w) => w.path === s.cwd);
  if (wt) {
    const repo = worktrees.repos.find((r) => r.id === wt.repoId);
    const branch = wt.branch ?? wt.head.slice(0, 7);
    return repo ? `${repo.label} · ${branch}` : branch;
  }
  return s.cwd.split('/').filter(Boolean).pop() ?? s.cwd;
}
</script>
