<template>
  <div class="flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
    <div class="flex shrink-0 items-center gap-1 px-2 text-[11px] font-semibold tracking-wide text-fg-subtle uppercase">
      <SquareTerminal :size="12" /> {{ t('ide.terminals') }}
    </div>

    <div
      v-for="sid in ide.dockSessionIds"
      :key="sid"
      class="group flex cursor-pointer items-center gap-1.5 border-l border-border px-2.5 text-xs select-none"
      :class="sid === ide.activeDockSessionId ? 'bg-surface-0 text-fg' : 'text-fg-muted hover:bg-surface-2/50'"
      :title="titleFor(sid)"
      @click="ide.focusTerminal(sid)"
      @mousedown.middle.prevent="ide.closeTerminal(sid)"
    >
      <SessionStateBadge v-if="sessionOf(sid)" :session="sessionOf(sid)!" />
      <span class="truncate font-mono">{{ titleFor(sid) }}</span>
      <button
        type="button"
        class="ml-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-surface-3"
        :title="t('common.close')"
        @click.stop="ide.closeTerminal(sid)"
      >
        <X :size="14" />
      </button>
    </div>

    <button
      type="button"
      class="ml-auto shrink-0 px-2 text-fg-subtle transition-colors hover:bg-surface-2 hover:text-fg"
      :title="t('common.close')"
      @click="ide.toggleBottom()"
    >
      <ChevronDown :size="14" />
    </button>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ChevronDown, SquareTerminal, X } 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 sessionOf = (sid: string): SessionSummary | null => sessions.sessions.find((s) => s.id === sid) ?? null;

// libellé compact : « repo · branche » si le worktree est connu, sinon le dernier segment du cwd.
function titleFor(sid: string): string {
  const s = sessionOf(sid);
  if (!s) return sid.slice(0, 8);
  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>
