<template>
  <div class="flex h-full min-h-0 flex-col">
    <template v-if="activeWt">
      <CommitPanel
        :repo-id="activeWt.repoId"
        :wt="activeWt.path"
        :changes="changes"
        :git="activeWt.git"
        :truncated="truncated"
        :active="activeFile"
        @select="onSelect"
        @changed="load"
      />
    </template>
    <div v-else class="flex h-full items-center justify-center p-4">
      <EmptyState :icon="GitCompare" :title="t('ide.activity.git')" :hint="t('workspace.noFileHint')" />
    </div>
  </div>
</template>

<script setup lang="ts">
// Panneau Git de l'IDE : cible le worktree actif (ide.activeContext), charge ses changements et
// s'abonne aux modifications disque. Réutilise CommitPanel (staging, commit, fetch/pull) tel quel.
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { GitCompare } from '@lucide/vue';
import type { FileChange } from '@arboretum/shared';
import { useIdeStore, tabId } from '../../stores/ide';
import { useWorktreesStore } from '../../stores/worktrees';
import { gitApi } from '../../lib/git-api';
import { wsClient } from '../../lib/ws-client';
import CommitPanel from '../workspace/CommitPanel.vue';
import EmptyState from '../ui/EmptyState.vue';

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

const changes = ref<FileChange[]>([]);
const truncated = ref(false);

const activeWt = computed(() => {
  const c = ide.activeContext;
  if (!c) return null;
  return worktrees.worktrees.find((w) => w.repoId === c.repoId && w.path === c.wtPath) ?? null;
});

const activeFile = computed(() => {
  const tab = ide.activeTab;
  const wt = activeWt.value;
  return tab && wt && tab.repoId === wt.repoId && tab.wtPath === wt.path ? tab.file : null;
});

async function load(): Promise<void> {
  const wt = activeWt.value;
  if (!wt) {
    changes.value = [];
    truncated.value = false;
    return;
  }
  try {
    const res = await gitApi.changes(wt.repoId, wt.path);
    changes.value = res.changes;
    truncated.value = res.truncated;
  } catch {
    /* worktree transitoire / erreur réseau : on garde l'état précédent */
  }
}

function onSelect(sel: { file: string; staged: boolean }): void {
  const wt = activeWt.value;
  if (!wt) return;
  ide.openFile(wt.repoId, wt.path, sel.file, 'diff');
  ide.setTabView(tabId(wt.repoId, wt.path, sel.file), 'diff', sel.staged);
}

// (ré)abonnement disque ciblé sur le worktree actif ; rechargement des changements.
let unwatch: (() => void) | null = null;
watch(
  () => activeWt.value?.path,
  () => {
    unwatch?.();
    unwatch = null;
    void load();
    const wt = activeWt.value;
    if (wt) {
      unwatch = wsClient.watchWorktree(wt.repoId, wt.path, () => void load());
    }
  },
  { immediate: true },
);

onBeforeUnmount(() => unwatch?.());
</script>
