<script setup>
import { ref, watch } from 'vue'
import { useProjectsStore } from '../stores/projects'
import { useModalsStore } from '../stores/modals'
import { svnApi } from '../api/client'

const store = useProjectsStore()
const modals = useModalsStore()
const diffText = ref('')
const loading = ref(false)

watch(() => modals.diffOpen, async (open) => {
  const id = store.currentId?.value ?? store.currentId
  if (open && id) {
    loading.value = true
    diffText.value = ''
    try {
      const res = await svnApi.diff(id, modals.diffPath || undefined)
      diffText.value = res.data?.diff ?? res.data ?? ''
    } catch (e) {
      diffText.value = '获取差异失败: ' + (e.response?.data || e.message)
    } finally {
      loading.value = false
    }
  }
})
</script>

<template>
  <div v-if="modals.diffOpen" class="modal-overlay" @click.self="modals.closeDiff()">
    <div class="modal modal-lg">
      <div class="modal-header">
        <h3>差异</h3>
        <button class="modal-close" @click="modals.closeDiff()">&times;</button>
      </div>
      <div class="modal-body">
        <div v-if="loading" class="loading">加载中...</div>
        <pre v-else class="diff-content">{{ diffText || '(无差异)' }}</pre>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.modal { background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 8px; min-width: 400px; max-height: 80vh; display: flex; flex-direction: column; }
.modal-lg { width: 90vw; max-width: 800px; }
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 1rem; border-bottom: 1px solid var(--border-color); }
.modal-header h3 { margin: 0; font-size: 1rem; }
.modal-close { background: none; border: none; color: var(--text-secondary); font-size: 1.5rem; cursor: pointer; }
.modal-body { padding: 1rem; overflow: auto; }
.loading { color: var(--text-secondary); }
.diff-content { font-family: var(--font-mono), monospace; font-size: 12px; white-space: pre; margin: 0; color: var(--text-primary); }
</style>
