<template>
  <div class="sync-page">
    <!-- Status card -->
    <div class="card animate-in">
      <div class="card-head">
        <h3>云端同步</h3>
        <el-button size="small" @click="checkStatus" :icon="Refresh">刷新状态</el-button>
      </div>

      <!-- Enabled state -->
      <div v-if="syncStatus.enabled" class="sync-enabled">
        <!-- Connection info -->
        <div class="connection-card" :class="{ 'connection-error': !syncStatus.connected }">
          <div class="connection-icon">
            <svg v-if="syncStatus.connected" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="1.5">
              <path d="M22 11.08V12a10 10 0 11-5.93-9.14"/>
              <polyline points="22 4 12 14.01 9 11.01"/>
            </svg>
            <svg v-else width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--danger)" stroke-width="1.5">
              <circle cx="12" cy="12" r="10"/>
              <line x1="15" y1="9" x2="9" y2="15"/>
              <line x1="9" y1="9" x2="15" y2="15"/>
            </svg>
          </div>
          <div class="connection-info">
            <span class="connection-status" :class="{ 'status-error': !syncStatus.connected }">
              {{ syncStatus.connected ? '已连接' : '连接失败' }}
            </span>
            <span class="connection-url">{{ syncStatus.repo_url }}</span>
            <span v-if="syncStatus.error" class="connection-error-msg">{{ syncStatus.error }}</span>
          </div>
        </div>

        <!-- Action buttons -->
        <div class="sync-actions">
          <button class="sync-btn push" @click="doPush" :disabled="syncing">
            <div class="sync-btn-icon">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
                <polyline points="17,8 12,3 7,8"/>
                <line x1="12" y1="3" x2="12" y2="15"/>
              </svg>
            </div>
            <div class="sync-btn-info">
              <span class="sync-btn-name">推送到云端</span>
              <span class="sync-btn-desc">上传本地数据到 Gitea</span>
            </div>
          </button>
          <button class="sync-btn pull" @click="doPull" :disabled="syncing">
            <div class="sync-btn-icon">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
                <polyline points="7,10 12,15 17,10"/>
                <line x1="12" y1="15" x2="12" y2="3"/>
              </svg>
            </div>
            <div class="sync-btn-info">
              <span class="sync-btn-name">从云端拉取</span>
              <span class="sync-btn-desc">下载远程数据到本地</span>
            </div>
          </button>
        </div>

        <!-- Sync progress -->
        <div v-if="currentTask" class="progress-section animate-in">
          <div class="progress-header">
            <span class="progress-title">同步进度</span>
            <el-tag :type="statusType" size="small" effect="dark">{{ statusText }}</el-tag>
          </div>
          <div class="progress-bar-wrap">
            <div class="progress-bar-fill" :style="{ width: currentTask.progress + '%' }"></div>
          </div>
          <p class="progress-msg">{{ currentTask.message }}</p>

          <div v-if="logs.length > 0" class="sync-logs">
            <div v-for="(line, i) in logs" :key="i" class="log-line" :class="logCls(line)">{{ line }}</div>
          </div>
        </div>
      </div>

      <!-- Disabled state -->
      <div v-else class="sync-disabled">
        <div class="disabled-icon">
          <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="#d1d5db" stroke-width="1">
            <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
            <line x1="12" y1="9" x2="12" y2="13"/>
            <line x1="12" y1="17" x2="12.01" y2="17"/>
          </svg>
        </div>
        <h4>云端同步未启用</h4>
        <p>请在系统配置页面设置 Gitea 相关参数以启用同步功能。</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { useProcessingStore } from '../stores/processing'
import api from '../api'

const processingStore = useProcessingStore()

const syncing = ref(false)
const syncStatus = ref({ enabled: false, connected: false, repo_url: '', error: '' })

const currentTask = computed(() => {
  if (processingStore.taskSource === 'sync') return processingStore.currentTask
  return null
})
const logs = computed(() => processingStore.logs)

const statusType = computed(() => {
  const m: Record<string, string> = { pending: 'info', running: 'warning', completed: 'success', failed: 'danger' }
  return m[currentTask.value?.status || ''] || 'info'
})
const statusText = computed(() => {
  const m: Record<string, string> = { pending: '等待中', running: '同步中', completed: '已完成', failed: '已失败' }
  return m[currentTask.value?.status || ''] || ''
})

function logCls(line: string) {
  if (line.includes('失败') || line.includes('错误')) return 'err'
  if (line.includes('完成')) return 'ok'
  return ''
}

async function checkStatus() {
  try {
    const res = await api.get('/sync/status')
    syncStatus.value = res.data
  } catch {
    ElMessage.error('检查同步状态失败')
  }
}

async function doPush() {
  syncing.value = true
  try {
    await processingStore.startTask('/sync/push', undefined, 'sync')
  } catch (err: any) {
    ElMessage.error(err.response?.data?.detail || '推送失败')
  } finally {
    syncing.value = false
  }
}

async function doPull() {
  syncing.value = true
  try {
    await processingStore.startTask('/sync/pull', undefined, 'sync')
  } catch (err: any) {
    ElMessage.error(err.response?.data?.detail || '拉取失败')
  } finally {
    syncing.value = false
  }
}

onMounted(checkStatus)
</script>

<style scoped>
.sync-page {
  max-width: 800px;
}

/* ── Card ── */
.card {
  background: #fff;
  border: 1px solid var(--border-light);
  border-radius: 12px;
  padding: 20px;
  transition: box-shadow 0.2s;
}

.card:hover {
  box-shadow: var(--shadow-md);
}

.card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.card-head h3 {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
}

/* ── Connection info ── */
.connection-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 18px 20px;
  background: rgba(16,185,129,0.05);
  border: 1px solid rgba(16,185,129,0.15);
  border-radius: 12px;
  margin-bottom: 24px;
}

.connection-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: rgba(16,185,129,0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.connection-status {
  display: block;
  font-size: 15px;
  font-weight: 600;
  color: var(--success);
}

.connection-status.status-error {
  color: var(--danger);
}

.connection-url {
  display: block;
  font-size: 13px;
  color: var(--text-secondary);
  font-family: var(--font-mono);
  margin-top: 2px;
}

.connection-error {
  background: rgba(239,68,68,0.05);
  border-color: rgba(239,68,68,0.15);
}

.connection-error-msg {
  display: block;
  font-size: 12px;
  color: var(--danger);
  margin-top: 4px;
}

/* ── Sync actions ── */
.sync-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 24px;
}

.sync-btn {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 18px 20px;
  border: 1px solid var(--border-light);
  border-radius: 12px;
  background: #fff;
  cursor: pointer;
  transition: all 0.2s var(--ease-out);
  text-align: left;
}

.sync-btn:hover:not(:disabled) {
  border-color: var(--amber-400);
  box-shadow: 0 0 0 3px rgba(251,191,36,0.08);
  transform: translateY(-1px);
}

.sync-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.sync-btn-icon {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.sync-btn.push .sync-btn-icon {
  background: rgba(99,102,241,0.08);
  color: var(--info);
}

.sync-btn.pull .sync-btn-icon {
  background: rgba(16,185,129,0.08);
  color: var(--success);
}

.sync-btn-name {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
}

.sync-btn-desc {
  font-size: 12px;
  color: var(--text-muted);
  margin-top: 2px;
}

/* ── Progress ── */
.progress-section {
  padding: 20px;
  background: #fafbfc;
  border-radius: 12px;
  border: 1px solid var(--border-subtle);
}

.progress-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.progress-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
}

.progress-bar-wrap {
  height: 6px;
  background: #e5e7eb;
  border-radius: 3px;
  overflow: hidden;
}

.progress-bar-fill {
  height: 100%;
  background: linear-gradient(90deg, var(--amber-400), var(--amber-600, #d97706));
  border-radius: 3px;
  transition: width 0.4s var(--ease-out);
}

.progress-msg {
  margin-top: 8px;
  font-size: 13px;
  color: var(--text-secondary);
}

/* ── Logs ── */
.sync-logs {
  margin-top: 16px;
  background: #0f1117;
  border-radius: 10px;
  padding: 14px;
  font-family: var(--font-mono);
  font-size: 12px;
  line-height: 1.7;
  max-height: 200px;
  overflow-y: auto;
}

.log-line {
  color: #94a3b8;
  padding: 1px 0;
}

.log-line.err { color: #f87171; }
.log-line.ok { color: #34d399; }

/* ── Disabled state ── */
.sync-disabled {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 48px 0;
}

.disabled-icon {
  opacity: 0.5;
  margin-bottom: 4px;
}

.sync-disabled h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-secondary);
}

.sync-disabled p {
  font-size: 13px;
  color: var(--text-muted);
}
</style>
